0

I'll explain in an example:

template<typename T>
class Base{}

class A: public Base<A>{}

class foo(){
public:
   template<typename T>
   bool is_derived(){
      /* static check if T is derived from Base<T> */
   }
}

I found this trait to determine whether a class is a base of another.

My question is, how can I send template arguments to is_base_of from T if T is a pointer without specializing the boo template function?

I'd like to do something like this: if T is a pointer then if (is_base_of<Base<*T>,*T>) return true; if T is not a pointer then if (is_base_of<Base<T>,T>) return true;

Community
  • 1
  • 1
Loay
  • 483
  • 3
  • 18

2 Answers2

3

You may use std::remove_pointer traits:

class foo(){
public:
   template<typename T>
   bool is_derived() const {
      using type = std::remove_pointer_t<T>;
      static_assert(std::is_base_of<Base<type>, type>::value,
                    "type should inherit from Base<type>");
   }
};
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • Thank you, that solved it for me. On a side note, why can't i do type = std::remove_pointer_t; what does the "using keyword indicate? – Loay Jun 22 '16 at 00:07
  • it is the c++11 `typedef` syntax for `typedef std::remove_pointer_t type;` – Jarod42 Jun 22 '16 at 00:08
  • Without this shortcut, you will have to write `std::is_base_of>, std::remove_pointer_t>::value` – Jarod42 Jun 22 '16 at 00:09
1

Basically you have already answered yourself.

C++14

bool is_derived(){
    static_assert( std::is_base_of<Base<T>, std::remove_pointer_t<T>>::value );
}

C++11

bool is_derived(){
    static_assert( std::is_base_of<Base<T>, typename std::remove_pointer<T>::type>::value );
}

C++03 - wrapper over is_base_of you mentioned (using Boost.StaticAssert)

template<class Base, class Derived> struct my_is_base_of : is_base_of<Base, Derived> { };
template<class Base, class Derived> struct my_is_base_of<Base*, Derived*> : is_base_of<Base, Derived> { };

// ...

bool is_derived(){
    BOOST_STATIC_ASSERT( my_is_base_of<Base<T>, T>::value );
}
Jan Korous
  • 666
  • 4
  • 11