Simplest way to provide template specialization for derived classes

后端 未结 1 829
天命终不由人
天命终不由人 2021-01-05 20:04

I have the following scenario:

class my_base { ... }

class my_derived : public my_base { ... };


template
struct my_traits;
相关标签:
1条回答
  • 2021-01-05 20:34

    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.

    0 讨论(0)
提交回复
热议问题