我正在努力解决编译问题。给定一个用T模板化的Base类,它包含一个用U模板化的方法,我不能从派生类调用该方法。以下示例重现了我的问题:
#include <iostream>
#include <vector>
template <class T>
class Base
{
protected:
template <class U>
std::vector<U> baseMethod() const
{
return std::vector<U>(42);
}
};
template <class T>
class Derived : public Base<T>
{
public:
std::vector<int> derivedMethod() const
{
return baseMethod<int>();
}
};
int main ()
{
Derived<double> d;
std::vector<int> res = d.derivedMethod();
return 0;
}
编译结果:
t.cc:21:12: error: ‘baseMethod’ was not declared in this scope
t.cc:21:23: error: expected primary-expression before ‘int’
t.cc:21:23: error: expected ‘;’ before ‘int’
t.cc:21:26: error: expected unqualified-id before ‘>’ token
答案 0 :(得分:2)
您应该添加template
关键字,将baseMethod
视为dependent template名称:
std::vector<int> derivedMethod() const
{
return this->template baseMethod<int>();
}
在模板定义中,除非使用消歧关键字template
(或除非已将其设置为模板名称),否则不将当前实例化成员的从属名称视为模板名称)。
有关详细信息:Where and why do I have to put the "template" and "typename" keywords?