Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get an error trying to call a template member function with an explicit type parameter?

I don't get it, it seems to me that the call to f is completely unambiguous, but it fails to compile with expected primary-expression before ‘int’. If I comment out the line with the 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>();     } }; 
like image 255
Casey Rodarmor Avatar asked Feb 09 '11 08:02

Casey Rodarmor


People also ask

How do you call a function in a template?

Defining a Function TemplateA function template starts with the keyword template followed by template parameter(s) inside <> which is followed by the function definition. In the above code, T is a template argument that accepts different data types ( int , float , etc.), and typename is a keyword.

Which parameter is allowed for non type template?

Which parameter is legal for non-type template? Explanation: The following are legal for non-type template parameters:integral or enumeration type, Pointer to object or pointer to function, Reference to object or reference to function, Pointer to member.

Can a template parameter be a function?

A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.

Can we override template function in C++?

You cannot define a virtual template method. override only works for virtual methods, and you can only override methods with the same signature. method<bool>() is not the same as method<int>() .


1 Answers

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

this->template f<int>(); 

This is similar to the weirdness with typename that comes up with dependent types, except as applied to functions. In particular, if you leave out the template keyword, there's a parsing ambiguity between

this->f<int>() 

(what you intended), and

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

which makes no sense (hence your error). The use of the keyword template here disambiguates and forces the compiler to recognize that it's looking at a perfectly valid call to a templated member function rather than a garbled mass of symbols.

Hope this helps!

like image 62
templatetypedef Avatar answered Oct 25 '22 18:10

templatetypedef