Simplest way to provide template specialization for derived classes

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

I have the following scenario:

class my_base { ... }

class my_derived : public my_base { ... };


template
struct my_traits;
1条回答
  •  慢半拍i
    慢半拍i (楼主)
    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 
    
    struct base {};
    struct derived : base {};
    
    template < typename T, typename Enable = void >
    struct traits;
    
    template < typename T >
    struct traits< T, typename boost::enable_if>::type >
    {
      enum { value = 5 };
    };
    
    #include 
    int main()
    {
      std::cout << traits::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)
提交回复
热议问题