我想确保在以下模板化类B的定义中,类A派生自抽象类C.我可以这样做吗?
template <class A>
class B {
// A must derive from C
...
};
我正在使用C ++ 11。
答案 0 :(得分:4)
template <class A>
class B {
static_assert(std::is_base_of<C, A>::value
, "A must derive from C");
//...
};
请注意is_base_of<C, C>::value
为真,因此您可能还想使用std::is_same
来确保A
本身不是C
:
static_assert(std::is_base_of<C, A>::value && !std::is_same<C, A>::value
, "A must derive from C");
答案 1 :(得分:0)
总的来说这是一个SFINAE问题。
在C ++ 11中有更好的方法,但是如果你使用的是C ++ 03,你可以试试这样的东西:
template <class A>
class B {
public:
B() { dummy((A*)0); }
private:
void dummy(C *test) {}
};
即,使用类型C
的指针添加虚函数。然后从值为A*
的值的构造函数中调用它。对于A
未从C
派生的类型,无法编译。