Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

templated method on T inside a templated class on TT : Is that possible/correct

I have a class MyClass which is templated on typename T. But inside, I want a method which is templated on another type TT (which is unrelated to T).

After reading/tinkering, I found the following notation:

template <typename T>
class MyClass
{
   public :
      template<typename TT>
      void MyMethod(const TT & param) ;
} ;

For stylistic reasons (I like to have my templated class declaration in one header file, and the method definitions in another header file), I won't define the method inside the class declaration. So, I have to write it as:

template <typename T>     // this is the type of the class
template <typename TT>    // this is the type of the method
void MyClass<T>::MyMethod(const TT & param)
{
   // etc.
}

I knew I had to "declare" the typenames used in the method, but didn't know how exactly, and found through trials and errors.

The code above compiles on Visual C++ 2008, but: Is this the correct way to have a method templated on TT inside a class templated on T?

As a bonus: Are there hidden problems/surprises/constraints behind this kind of code? (I guess the specializations can be quite amusing to write)

like image 260
paercebal Avatar asked Apr 28 '10 12:04

paercebal


1 Answers

This is indeed the correct way of doing what you want to do, and it will work on every decent C++ compiler. I tested it on gcc4.4 and the latest clang release.

There are problems/surprises/constraints behind any kind of code.

The major issue you could eventually run in with this code is that you can't make a templated function virtual, so if you want to get polymorphism at the class level for your templated function, you're off implementing it with an external function.

like image 192
raph.amiard Avatar answered Nov 18 '22 18:11

raph.amiard