The easiest way to provide specialized specialization in derived classes

I have the following script:

class my_base { ... }

class my_derived : public my_base { ... };


template<typename X>
struct my_traits.

I want to specialize my_traitsall classes derived from my_base, including: ie

template<typname Y> // Y is derived form my_base.
stryct my_traits { ... };

I have no problem adding tags, members in my_base, to simplify it. I saw some kind of trick, but I still feel lost.

How can this be done, simply and briefly?

+3
source share
1 answer

Well, you do not need to write your own isbaseof. You can use boost or C ++ 0x.

#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 think they are better or worse than the alternative in another matter.

+1

Source: https://habr.com/ru/post/1748393/


All Articles