Why does an error occur when calling a member function of a template with an explicit type parameter?

I don’t understand, it seems to me that the call to f absolutely unambiguous, but it will not compile with the expected primary-expression before 'int' . If I comment on a line with a call to f , it compiles fine.

 template<typename T> struct A { template<typename S> void f() { } }; template<typename T> struct B : A<T> { void g() { this->f<int>(); } }; 
+68
c ++ templates metaprogramming
Feb 09 '11 at 8:29
source share
1 answer

This is due to the really obscure provision of the standard, in which if you have a template that is trying to access the template function in an object whose type depends on the template argument, you should use the template keyword in a weird way:

 this->template f<int>(); 

This is similar to the typename weirdness that occurs with dependent types, except as applied to functions. In particular, if you do not specify the template keyword, there is parsing uncertainty between

 this->f<int>() 

(what did you intend) and

 ((this->f) < int) > () 

which does not make sense (hence your mistake). Using the template keyword here disambiguates and forces the compiler to recognize that it is looking at a valid call to a template member function, rather than a distorted mass of characters.

Hope this helps!

+129
Feb 09 2018-11-11T00:
source share



All Articles