0

I want to specialize implementation of a template class if T was derived from a specific base class.

How can I do this?

In the code below, x.f() and y.f() should do different work.

I want to work not only for 'Derived' but also for all derived classes from Base.

#include <iostream>

class Base
{
};

class Derived : public Base
{
};

// If T not derived from Base:
template <typename T> class MyClass
{
public:
   void f()
   {
      std::cout << "NOT derived from Base";
   }
};

// If T derived from Base:
template <typename T> class MyClass
{
public:
   void f()
   {
      std::cout << "Derived from Base";
   }
};

int main()
{
   MyClass<int> x;
   MyClass<Derived> y;
   x.f();
   y.f();
}
A.Danesh
  • 844
  • 11
  • 40
  • 1
    Following may help : https://ideone.com/tlxtbs – Jarod42 Oct 02 '14 at 13:15
  • More often than not what you **really** want to specialize templates based on the traits of the the parameter class, not based of the inheritance of the parameter. In which case...use traits helper class. – ArunasR Oct 02 '14 at 13:28

1 Answers1

1

Can use following :

#include <type_traits>

//If T not derived from Base:
template<class T, class Enable = void> class MyClass
{
public:
   void f()
   {
      std::cout << "NOT derived from Base";
   }
};


template<typename T>
class MyClass<T,typename std::enable_if<std::is_base_of<Base, T>::value>::type> 
{
 public:
   void f()
   {
      std::cout << "\nDerived from Base";
   }
}; 

See Here

P0W
  • 46,614
  • 9
  • 72
  • 119