开发者

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 m开发者_如何学编程ethod 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)


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜