Reputation: 6835
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;
}
Calling to
in the main works, but I can't figure out why it doesn't when called in Base()
. The error I get is:
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’
Upvotes: 2
Views: 1492
Reputation: 81349
Because t
is of type Test<Real>
where Real
is a template argument, so the type of t
is actually a dependent type. You need to let the compiler know to
is a template function by using:
_i = t.template to<int>();
Otherwise you could be attempting to use the operator<
on a member of t
called to
(causing some errors), which is what the compiler assumes unless you mark it template
. When called from main
, the type of t1
is Test<double>
which is not dependent on any template argument so the compiler can figure on its own its a template function.
Upvotes: 4