模板化类中的模板化函数

时间:2017-05-25 11:00:47

标签: c++ templates gcc

template <typename T>
class Foo {
public:
    template <int x>
    void bar () {}
};

以下编译:

void fooBar ()
{
    Foo<int> f;
    f.bar<1>();
}

但是以下内容没有(&#34;错误:在&#39之前预期的primary-expression;)&#39;令牌&#34;在gcc 5.4.0中使用-std = c ++ 14)。

template <typename T>
void fooBar ()
{
    Foo<T> f;
    f.bar<1>();
}

如果我尝试显式调用第二个版本,例如

fooBar<int>();

然后gcc另外抱怨

"invalid operands of types '<unresolved overloaded function type>' and 'int' to binary 'operator<'".

第二个版本无效是否有任何原因?为什么gcc会对待&#39;&lt;&#39;作为运算符而不是模板参数列表的开头?

1 个答案:

答案 0 :(得分:15)

使用模板化函数,编译器并不确切知道Foo<T>究竟是什么(可能有Foo的特化),所以它必须假设f.bar是一个成员变量并将代码解析为

f.bar < 1

然后它无法继续。

您可以通过告诉bar是模板

来帮助编译器
f.template bar<1>();