c++ template specialization for all subclasses

后端 未结 5 586
隐瞒了意图╮
隐瞒了意图╮ 2020-12-30 09:27

I need to create a template function like this:

template
void foo(T a)
{
   if (T is a subclass of class Bar)
      do this
   else
      d         


        
5条回答
  •  生来不讨喜
    2020-12-30 10:04

    I would use std::is_base_of along with local class as :

    #include   //you must include this: C++11 solution!
    
    template
    void foo(T a)
    {
       struct local
       {
            static void do_work(T & a, std::true_type const &)
            {
                //T is derived from Bar
            }
            static void do_work(T & a, std::false_type const &)
            {
                //T is not derived from Bar
            }
       };
    
       local::do_work(a, std::is_base_of());
    }
    

    Please note that std::is_base_of derives from std::integral_constant, so an object of former type can implicitly be converted into an object of latter type, which means std::is_base_of() will convert into std::true_type or std::false_type depending upon the value of T. Also note that std::true_type and std::false_type are nothing but just typedefs, defined as:

    typedef integral_constant  true_type;
    typedef integral_constant false_type;
    

提交回复
热议问题