LxL*_*LxL 2 c++ templates c++11
我有一个这样的课:
template <class T1, class T2>
class A
{
//Error if Base class of T2 is not T1 (At compile time)
};
Run Code Online (Sandbox Code Playgroud)
我想检查一下是否T1是Base类T2.可以在编译时吗?
一些例子 :
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
//.....
Run Code Online (Sandbox Code Playgroud)
std::is_base_of会让你在那里大部分时间,但它不是你想要的.如果两种类型相同,您还需要一个错误,并且is_base_of<T, T>::value始终true用于任何用户定义的类型T.结合检查std::is_same以获得您想要的行为.
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");
};
Run Code Online (Sandbox Code Playgroud)
这将导致以下结果:
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
Run Code Online (Sandbox Code Playgroud)