Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ template specialization for all subclasses

I need to create a template function like this:

template<typename T>
void foo(T a)
{
   if (T is a subclass of class Bar)
      do this
   else
      do something else
}

I can also imagine doing it using template specialization ... but I have never seen a template specialization for all subclasses of a superclass. I don't want to repeat specialization code for each subclass

like image 297
Abhishek Anand Avatar asked Jan 08 '12 03:01

Abhishek Anand


1 Answers

I know this question has been answered but nobody mentioned that std::enable_if can be used as a second template parameter like this:

#include <type_traits>

class A {};
class B: public A {};

template<class T, typename std::enable_if<std::is_base_of<A, T>::value, int>::type = 0>
int foo(T t)
{
    return 1;
}
like image 66
Elviss Strazdins Avatar answered Oct 05 '22 02:10

Elviss Strazdins