Template specialization based on inherit class

This article describes a neat trick: http://www.gotw.ca/publications/mxc++-item-4.htm Here’s the basic idea. You first need an IsDerivedFrom class (this provides runtime and compile-time checking): template<typename D, typename B> class IsDerivedFrom { class No { }; class Yes { No no[3]; }; static Yes Test( B* ); // not defined static No Test( … ); // not … Read more

Default template argument and partial specialization

The default argument applies to the specialization — and, in fact, a specialization must accept (so to speak) the base template’s default argument(s). Attempting to specify a default in the specialization: template<class A = int, class B=double> class Base {}; template<class B=char> // … …is an error. Likewise, if we change the specialization so that … Read more

Default template parameter partial specialization

The default argument applies to the specialization — and, in fact, a specialization must accept (so to speak) the base template’s default argument(s). Attempting to specify a default in the specialization: template<class A = int, class B=double> class Base {}; template<class B=char> // … …is an error. Likewise, if we change the specialization so that … Read more

static member initialization for specialized template class

For static member specializations, if you don’t initialize the member, it is taken as a specialization declaration, that just says “Oh, don’t instantiate the member from the primary template, because there is a specialized definition somewhere else”. It should be mentioned that the definition should appear in a .cpp file (otherwise, you will earn the … Read more

Template specialization of a single method from a templated class

As with simple functions you can use declaration and implementation. Put in your header declaration: template <> void TClass<int>::doSomething(std::vector<int> * v); and put implementation into one of your cpp-files: template <> void TClass<int>::doSomething(std::vector<int> * v) { // Do somtehing with a vector of int’s } Don’t forget to remove inline (I forgot and thought this … Read more

Selecting a member function using different enable_if conditions

enable_if works because the substitution of a template argument resulted in an error, and so that substitution is dropped from the overload resolution set and only other viable overloads are considered by the compiler. In your example, there is no substitution occurring when instantiating the member functions because the template argument T is already known … Read more