1
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’
現在,它是一個靜態成員? –
好的,靜態模板成員應該在模板結構或類名後面有'template'關鍵字:'Test :: template to(...)'。當然,從超自由的MSVC移植到G ++時,你只會開始考慮它。如果你喜歡在晚上睡覺,C++不適合你。 –