c++ - 变量类派生自某个抽象类的类模板

标签 c++ templates c++11 abstract-class

我想确保在以下模板化类 B 的定义中,类 A 派生自抽象类 C。我可以这样做吗?

template <class A>
class B {
    // A must derive from C
    ...
};

我正在使用 C++11。

最佳答案

使用 std::is_base_of :

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");

关于c++ - 变量类派生自某个抽象类的类模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17978322/

相关文章:

c++ - 为什么基本类型不允许标准库类上的extern模板

c++ - 模板化成员函数指针作为模板参数

c++ - 将内部函数作为模板参数传递

C++ 运算符 []

c++ - 是否存在用于将 C++ 代码移植到 64 位的自动转换工具?

c++ - STL 和多线程

c++ - 在 C++ 中将指针传递给函数

c++ - 引用 vector 中的对象(现代 C++)

c++ - 通过右值引用获取参数的所有权

c++ - 循环 typedef 列表