Possible Duplicate:
Where and why do I have to put the “template” and “typename” keywords?
代码如下:
template<typename T>
class base
{
public:
virtual ~base();
template<typename F>
void foo()
{
std::cout << "base::foo<F>()" << std::endl;
}
};
template<typename T>
class derived : public base<T>
{
public:
void bar()
{
this->foo<int>(); // Compile error
}
};
并且,在运行时:
derived<bool> d;
d.bar();
我收到以下错误:
error: expected primary-expression before ‘int’
error: expected ‘;’ before ‘int’
我知道non-dependent names and 2-phase look-ups .但是,当函数本身是模板函数(我的代码中的 foo<>()
函数)时,我尝试了所有变通方法都失败了。
最佳答案
foo
是一个依赖名称,因此第一阶段查找假定它是一个变量,除非您使用 typename
或 template
关键字另有说明。在这种情况下,您需要:
this->template foo<int>();
见 this question如果你想要所有血淋淋的细节。
关于c++ - 调用模板基类的模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9289859/