Yesterday I went and wanted to convert a function into a templated function in C++. No big deal, but one of my constructs gave me some problems. I’ll illustrate with an example function, that contains the problem I had
void myfunc( int a ) {
some_class::some_method<some_class>( a );
}
There are good reasons for some_method to be templated with some_class, which has to do with the fact that some_method is static and needs to interface to some C code, that expects static callbacks, and what not.
I wanted to make this work for both some_class, and some_other_class. Here is my first try:
template <class T>
void myfunc( int a ) {
T::some_method<T>( a );
}
This declaration/definition does not work. The compiler wants a primary expression before the first >,and complains about the “,” operator ignoring its first argument.
I was a bit stumped by this, but got some help from ##c++ on irc.freenode.net.
Here is the right way to write it:
template <class T>
void myfunc( int a ) {
T::template some_method<T>( a );
}
Turns out, that when the compiler needs to figure out what some_method is, it can not look in T for help. So, it assumes that some_method is not a templated function, and the first ‘<’ is interprented as operator<. This also explains why it want a primary expression, and why it complains about operator,.
The solution: Let the compiler know that some_method is templated, by inserting “template ” before the method call.