jeudi 12 novembre 2020

Using std::enable::if and std::is_base_of to constraint inherintance

Given the following scenario:

class A {};
class B : public A {};
class C : public A {};
class D : public A {};

template<typename T/*std::enable_if and std::is_base_of here*/> class X {};

When I declare an X

Then I want to constraint the typename T to obligatorily be a sub-class of A, otherwise I'll get a compiling error.

int main()
{
   X<B> x1 = {}; //should work;
   X<C> x2 = {}; //should work;
   X<D> x2 = {}; //should work;
   X<std::string> = {};  //should generate a compiling error;
   X<int> = {};  //should generate a compiling error;
};

Aucun commentaire:

Enregistrer un commentaire