How to restrict the instantiation of a class based on the ancestry of the templated type

Viewed 77

I have a templated class XX and would like to restrict the instantiation of it to only types T that are descendants of another class 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;
    // ...
};

Using Visual Studio 2019 C++ (ISO C++17) I am getting

error C2275: 'std::is_base_of<ZZ, T>': illegal use of this type as an expression

Is this not the proper way to use std::is_base_of<>?

1 Answers

std::is_base_of is a type, which can't be used as a condition in static_assert. You're looking for std::is_base_of_v instead:

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

or pre-C++17, you can do:

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