I have a class like this :
template <class T1, class T2>
class A
{
//Error if Base class of T2 is not T1 (At compile time)
};
I want to check if T1 is Base class of T2 . Is is possible at compile time ?
Some Examples :
class C{};
class B :public C{};
A< C, B > a; //Ok because C is base class of B
A<B, C> b; //Error B is not base class of C
A<char, char> c; //Error char is not base class of char
//.....
std::is_base_of will get you most of the way there, but it's not quite what you want. You also want an error if the two types are the same, and is_base_of<T, T>::value is always true for any user defined type T. Combine the check with std::is_same to get the behavior you want.
template <class T1, class T2>
class A
{
static_assert(std::is_base_of<T1, T2>::value &&
!std::is_same<T1, T2>::value,
"T1 must be a base class of T2");
};
This will result in the following:
A< C, B > a; //Ok because C is base class of B
A<B, C> b; //Error B is not base class of C
A<char, char> c; //Error char is not base class of char
A<B, B> d; //Error B is not base class of B <-- this won't fail without
// the is_same check
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With