首页 > 解决方案 > 从模板化方法调用模板方法的问题

问题描述

我有一个小的模板结构,它将调用转发到另一个模板结构。应该很简单。但我面临一个问题。这个想法是 One 结构使用模板参数来转发调用,具体取决于作为参数传递的编译时间常量。

这是我设法重现该问题的最少代码:

struct OutFoo
{
template <bool Condition>
static constexpr void foo_ce() noexcept
{
}

static constexpr void foo() noexcept
{
}

};

template <typename OF>
struct InnerFoo
{
template <bool b>
static constexpr void inner_foo() noexcept
{
//    OF::foo_ce<b>();        // Does not compile
//    OF::foo_ce<true>();     // Does not compile
    OF::foo();
}
};

int main()
{
    InnerFoo<OutFoo>::inner_foo<true>();
}

我的理解是,注释掉的两行都应该编译,因为应该采用 OF(又名 OutFoo,然后应该调用 foo_ce()。

这实际上适用于 MSVC,但不适用于 gcc。谁是对的?我究竟做错了什么?

https://godbolt.org/z/PoGv6r

gcc 错误:

source>: In static member function 'static constexpr void InnerFoo<OF>::inner_foo()':
<source>:22:19: error: expected primary-expression before ')' token
   22 |     OF::foo_ce<b>();
      |                   ^
<source>:23:22: error: expected primary-expression before ')' token
   23 |     OF::foo_ce<true>();
      |                      ^
<source>: In instantiation of 'static constexpr void InnerFoo<OF>::inner_foo() [with bool b = true; OF = OutFoo]':
<source>:30:39:   required from here
<source>:22:15: error: invalid operands of types '<unresolved overloaded function type>' and 'bool' to binary 'operator<'
   22 |     OF::foo_ce<b>();
      |         ~~~~~~^~
<source>:23:15: error: invalid operands of types '<unresolved overloaded function type>' and 'bool' to binary 'operator<'
   23 |     OF::foo_ce<true>();
      |         ~~~~~~^~~~~

clang 错误更清楚:

<source>:22:9: error: missing 'template' keyword prior to dependent template name 'foo_ce'
    OF::foo_ce<b>();
        ^     ~~~
<source>:23:9: error: missing 'template' keyword prior to dependent template name 'foo_ce'
    OF::foo_ce<true>();
        ^     ~~~~~~
2 errors generated.

标签: c++gccvisual-c++-6

解决方案


推荐阅读