我有一些正在修改的模板代码,但遇到了一个我无法解决的奇怪错误。我能够使用以下更简单(但毫无意义)的代码片段重现问题:
struct Widget
{
};
template <typename A>
class Foo
{
public:
template <int numA>
inline bool funcCall()
{
return numA > 0;
}
inline bool funcCallNoTemplate()
{
return false;
}
};
template <typename B>
class Bar : public Foo<B>
{
public:
// doesn't work
bool concrete()
{
return Foo<B>::funcCall<5>();
}
// works fine
bool other()
{
return Foo<B>::funcCallNoTemplate();
}
};
int main()
{
Bar<Widget> b;
b.concrete();
b.other();
return 0;
}
我在 GCC 4.7 中遇到的错误如下(第 30 行是 Bar::concrete 的主体):
example.cxx: In member function ‘bool Bar<B>::concrete()’:
example.cxx:30: error: expected primary-expression before ‘)’ token
example.cxx: In member function ‘bool Bar<B>::concrete() [with B = Widget]’:
example.cxx:43: instantiated from here
example.cxx:30: error: invalid operands of types ‘<unresolved overloaded function type>’ and ‘int’ to binary ‘operator<’
似乎编译器甚至无法正确解析它,我是否遗漏了一些使该行完全虚假的东西?
最佳答案
It seems like the compiler can't even parse this correctly, am I missing something here that makes that line completely bogus?
是的。您需要使用 template
消歧器:
return Foo<B>::template funcCall<5>();
// ^^^^^^^^
这样你会告诉编译器解析依赖名称funcCall
作为成员函数模板的名称,随后的尖括号作为相应模板参数的分隔符。
没有它,funcCall
将被解析为数据成员的名称,而 <
和 >
将分别被解析为小于和大于。
关于c++ - 从模板类继承和调用模板函数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16597775/