【问题标题】:How to restrict the instantiation of a class based on the ancestry of the templated type如何根据模板类型的祖先限制类的实例化
【发布时间】:2020-10-17 21:28:39
【问题描述】:

我有一个模板类 XX,并希望将其实例化限制为仅类型 T 是另一个类 ZZ 的后代:

class ZZ {
public:
    int transmorgificationFactor;
};

template <typename T>
class XX {
public:
    static_assert(std::is_base_of<ZZ, T>, "T must be a ZZ");
    T foo;
    // ...
};

我正在使用 Visual Studio 2019 C++ (ISO C++17)

error C2275: 'std::is_base_of': 非法使用这种类型作为 表达

这不是使用std::is_base_of&lt;&gt;的正确方法吗?

【问题讨论】:

    标签: c++ templates inheritance c++17 typetraits


    【解决方案1】:

    std::is_base_of 是一个类型,不能在static_assert 中用作条件。您正在寻找 std::is_base_of_v 代替:

    static_assert(std::is_base_of_v<ZZ, T>, "T must be a ZZ");
                              // ^^
    

    或 C++17 之前的版本,您可以这样做:

    static_assert(std::is_base_of<ZZ, T>::value, "T must be a ZZ");
                                     // ^^^^^^^
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-08
      • 2017-09-07
      相关资源
      最近更新 更多