【问题标题】:Templated function in templated class [duplicate]模板类中的模板函数[重复]
【发布时间】:2017-10-26 00:13:23
【问题描述】:

与

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

以下编译:

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

但以下没有(在 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&lt;&gt;();的功能是什么?它存在于哪里?
  • @alhadhrami 对不起 - 应该读过 fooBar。在编辑中更正。

标签: c++ templates gcc


【解决方案1】:

使用模板化函数,编译器并不确切知道Foo&lt;T&gt; 将是什么(Foo 可能有特化),因此它必须假设f.bar 是一个成员变量并解析代码作为

f.bar < 1

然后就无法继续了。

你可以告诉编译器bar是一个模板来帮助它

f.template bar<1>();

【讨论】:

  • 这行得通——而且我以前从未见过这种语法。我从来没有想过尝试这个。谢谢!
猜你喜欢
  • 2016-05-23
  • 2016-02-25
  • 1970-01-01
  • 1970-01-01
  • 2016-04-06
  • 2012-01-28
  • 2023-03-13
相关资源
最近更新 更多