微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 模板类中的模板化函数

参见英文答案 > Where and why do I have to put the “template” and “typename” keywords?6个
template <typename T>
class Foo {
public:
    template <int x>
    void bar () {}
};

以下编译:

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

但是以下内容没有(带有“错误:在’之前预期的primary-expression’)’令牌”在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处理’<'作为运算符而不是模板参数列表的开头?

解决方法

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

然后它无法继续.

您可以通过告诉编译器栏是模板来帮助编译器

f.template bar<1>();

原文地址:https://www.jb51.cc/c/119740.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐