如何根据模板类型的祖先限制 class 的实例化
How to restrict the instantiation of a class based on the ancestry of the templated type
我有一个模板化的 class XX
并且想将它的实例化限制为仅属于另一个 class [=14= 的后代的类型 T
]:
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<ZZ, T>': illegal use of this type as an
expression
这不是std::is_base_of<>
的正确使用方法吗?
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");
// ^^
或pre-C++17,你可以这样做:
static_assert(std::is_base_of<ZZ, T>::value, "T must be a ZZ");
// ^^^^^^^
我有一个模板化的 class XX
并且想将它的实例化限制为仅属于另一个 class [=14= 的后代的类型 T
]:
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<ZZ, T>': illegal use of this type as an expression
这不是std::is_base_of<>
的正确使用方法吗?
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");
// ^^
或pre-C++17,你可以这样做:
static_assert(std::is_base_of<ZZ, T>::value, "T must be a ZZ");
// ^^^^^^^