Smplest way to provide template specialization for derived classes

二次信任 提交于 2019-12-19 09:09:15

问题


I have following scenario:

class my_base { ... }

class my_derived : public my_base { ... };


template<typename X>
struct my_traits.

I want to specialize my_traits all classes derived from my_base including: i.e.

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

I have no problems to add any tags, members to my_base to make it simpler. I've seen some trick but I still feel lost.

How can this be done is simple and short way?


回答1:


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.



来源:https://stackoverflow.com/questions/2968380/smplest-way-to-provide-template-specialization-for-derived-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!