问题
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