c++ – How to set restrictions on parameters of template classes?

Question:

There is an abstract class M and classes A , B and C , for which М is the parent class, and all the abstract methods of class М are implemented in them.
Need to create a template class

template <class T> class S{ ... };

which uses the classes A , B , or C as the template. Can I somehow specify that M should be the parent class of Т ?

Answer:

std::is_base_of will save you:

struct M {};

struct A: public M {};

struct B {};

template<class T, typename=std::enable_if_t<std::is_base_of<M,T>::value>>
struct S {};


int main(int argc, const char * argv[])
{
    S<A> a;
    S<B> b;
}
Scroll to Top