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 fee开发者_运维技巧l lost.
How can this be done in a simple and short way?
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.
精彩评论