5

I have the following scenario:

class my_base { ... }

class my_derived : public my_base { ... };


template<typename X>
struct my_traits;

I want to specialize my_traits for all classes derived from my_base including, e.g.:

template<typename Y> // Y is derived form my_base.
struct my_traits { ... };

I have no problems with adding tags, members to my_base to make it simpler. I've seen some tricks but I still feel lost.

How can this be done in a simple and short way?

Don Hatch
  • 5,041
  • 3
  • 31
  • 48
Artyom
  • 31,019
  • 21
  • 127
  • 215
  • Duplicate of http://stackoverflow.com/questions/281725/template-specialization-based-on-inherit-class, if that's good enough. – Beta Jun 03 '10 at 18:06
  • @Beta, isn't there simpler way? As I can arbitrary change my_base so maybe it can be done without IsBaseOf? – Artyom Jun 03 '10 at 18:12
  • Simpler in c++11 : http://stackoverflow.com/a/25934222/1132686 – A.Danesh Oct 02 '14 at 13:17

1 Answers1

3

Well, you don't need to write your own isbaseof. You can use boost's or c++0x's.

#include <boost/utility/enable_if.hpp>

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

template < typename T, typename Enable = void >
struct traits;

template < typename T >
struct traits< T, typename boost::enable_if<std::is_base_of<base, T>>::type >
{
  enum { value = 5 };
};

#include <iostream>
int main()
{
  std::cout << traits<derived>::value << std::endl;

  std::cin.get();
}

There are scaling issues but I don't believe they're any better or worse than the alternative in the other question.

Edward Strange
  • 40,307
  • 7
  • 73
  • 125
  • Thanks... It looks there is nothing simpler around, but these is at least is done with one line (and few headers) – Artyom Jun 03 '10 at 18:23