Why can I not call templated method of templated class from a templated function [duplicate]
Possible Duplicate:
Confusing Template error 开发者_高级运维
I have a templated class with a templated method. Now I have another function, with 2 template arguments creating the class with the first template argument and calling the function with the second. Consider this example:
template<class S>
class A {
public:
template<class T>
T f1() {
return (T)0.0;
}
};
template<class T,class CT>
void function() {
A<T> a;
a.f1<CT>(); // gcc error in this line
}
gcc gived me:
error: expected primary-expression before ‘>’ toke
in the line marked above. Why does this not work and how can I fix it? Thanks! Nathan
A<T>
is a dependent type (i.e. it depends on the template parameter T
), so you have to specify that you're referring to a template member:
a.template f1<CT>();
You can, but you need to help the compiler.
Because a
has a dependent type, the compiler cannot assume what a.f1
refers to. It could be a type, a constant, a function... whatever.
Because the template syntax uses <
it is easily confused with the operator<
.
Therefore the Standard requires that you disambiguates the nature of elements within a dependent type. This applies both to:
- types, with the use of
typename
, such astypedef typename A<T>::SomeType type;
- functions, with the use of
template
, such asa.template f1<CT>();
It can be argued that since it is known that CT
is a type, such a disambiguation is meaningless, but things get hairy when it involves functions being passed as type parameters.
For example a.f1<CT()>();
can be interpreted either as:
- Compare
a.f1
and a default constructedCT
usingoperator<
- Call
a.f1
with aCT()
as template parameter
The C++ syntax is (for once) uniform and requires disambiguation in all cases.
A quality compiler will suggest to you the appropriate fix when it can makes sense of your construct.
精彩评论