template <class T>
class Test{
public:
Test(T){ }
template <class U>
U to() const{ return U(0); }
};
template <class Real>
class Base{
typedef Test<Real> TST;
protected:
Base(const TST& t){
_i = t.to<int>(); // <- but this gives error
}
int _i;
};
template <class Real, class T> class Child;
template <class Real>
class Child<Real, int> : public Base<Real>{
typedef Base<Real> F;
typedef Test<Real> TST;
public:
Child() : F(TST(23.0)){ }
};
int main(int argc, char* argv[]){
Child<double, int> rw;
Test<double> t1(3.3);
int i = t1.to<int>(); // <- this works
return 0;
}
在主要工作中调用to
,但我不明白为什么在Base()
中调用时它不起作用。我得到的错误是:
t1.cpp: In constructor ‘Base<Real>::Base(const TST&)’:
t1.cpp:20:15: error: expected primary-expression before ‘int’
t1.cpp:20:15: error: expected ‘;’ before ‘int’
最佳答案
因为t
类型为Test<Real>
哪里Real
是一个模板参数,所以 t
的类型实际上是一个依赖类型。你需要让编译器知道to
是一个模板函数,使用:
_i = t.template to<int>();
否则您可能会尝试使用 operator<
关于 t
的成员叫to
(导致一些错误),这是编译器假设的,除非您将其标记为 template
。当从 main
调用电话时,类型 t1
是 Test<double>
它不依赖于任何模板参数,因此编译器可以自行计算出它的模板函数。
关于c++ - 为什么调用模板成员函数会出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7871614/