7

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)

paercebal
  • 81,378
  • 38
  • 130
  • 159
  • 1
    As for specializations: you can't specialize a member function without explicitly specializing the containing class: http://stackoverflow.com/questions/2097811/c-syntax-for-explicit-specialization-of-a-template-function-in-a-template-class/2114807 – Georg Fritzsche Apr 28 '10 at 22:59

2 Answers2

3

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.

raph.amiard
  • 2,755
  • 2
  • 20
  • 23
0

I think It's OK to do that. Take a look for example at std::vector implementation. You have class vector, which has a few template parameters (most notably an element type), and inside, one of its constructors is declared in similar way as your method. It has InputIterator as a template parameter. So I think that this is not so uncommon practice.

iwasz
  • 128
  • 3
  • 6