san
san

Reputation: 4254

Specializing a class template by a base class

I have distilled my doubt to this following piece of code

struct base {};
struct derived : public base {};

template <class T>
struct Type { };

template <> struct Type<base> {
  typedef float mytype;
};

typename Type<base>::mytype a=4.2;    // this works
typename Type<derived>::mytype a=4.2; // this doesnt

Could anyone explain why I cannot intantiate the class template object with derived and suggest a simple way to do it. For the actual problem that I am interested in there are many derived classes using which I want to intantiate template class objects and/or use typedefs. There are too many of them than what I would want to specialize individually.

EDIT: Forgot to mention, my bad, this needs to be C++03

Upvotes: 3

Views: 1272

Answers (2)

ildjarn
ildjarn

Reputation: 62975

#include <iostream>
#include <type_traits>

struct base { };
struct derived : base { };

template<typename T, bool = std::is_base_of<base, T>::value>
struct Type { };

template<typename T>
struct Type<T, true>
{
   typedef float mytype;
};

int main()
{
   Type<base>::mytype a1 = 4.2f;
   Type<derived>::mytype a2 = 8.4f;
   std::cout << a1 << '\n' << a2 << '\n';
}

In C++03, std can be trivially replaced with boost: boost::is_base_of

Upvotes: 4

Two instantiations of a template class with different template arguments are totally unrelated class types. Type<derived> has no relation whatsoever to Type<base>, which of course means it doesn't use the specialisation and is instantiated from the primary template. The primary template has no nested type mytype.

Upvotes: 3

Related Questions