I made the following program
#include <iostream>
#include <typeinfo>
template<class T>
struct Class
{
template<class U>
void display(){
std::cout<<typeid(U).name()<<std::endl;
return ;
}
};
template<class T,class U>
void func(Class<T>k)
{
k.display<U>();
}
int main()
{
Class<int> d;
func<int,double>(d);
}
The above program doesn not compile because display() is a template member function so a qualification of .template before display() must be done. Am I right?
But when I made the following program
#include <iostream>
#include <typeinfo>
template<typename T>
class myClass
{
T dummy;
/*******/
public:
template<typename U>
void func(myClass<U> obj);
};
template<typename T>
template<typename U>
void myClass<T>::func(myClass<U> obj)
{
std::cout<<typeid(obj).name()<<std::endl;
}
template<class T,class U>
void func2(myClass<T>k)
{
k.template func<U>(k); //even it does not compile
}
int main()
{
myClass<char> d;
func2<char,int>(d);
std::cin.get();
}
Why k.func<char>(k); does not compile even after giving a .template construct?
The
<symbol means both “less than” and “begin template arguments.” To distinguish between these two meanings, the parser must know whether the preceding identifier names a template or not.For example consider the code
Either
T::variableorT::constantmust be a template. The function means different things depending which is and which isn’t:T::constantgets compared to 3 and the Boolean result becomes a template argument toT::variable<>T::constant<3>gets compared tox->variable.The to disambiguate, the
templatekeyword is required before eithervariableorconstant. Case 1:Case 2:
It would be kind of nice if the keyword were only required in actual ambiguous situations (which are kind of rare), but it makes the parser much easier to write and it prevents such problems from catching you by surprise.
For standardese, see 14.2/4: