mercredi 5 avril 2017

Using std::enable_if to enable a templated constructor and a function that returns another templated instance

I want to make a templated class, MyClass<T>, where I want to have a templated constructor that will take a single argument of type MyClass<U>, that will work only if U is derived from T (or the same as T, essentially also acting as a copy constructor in that case). If it is not, I want to fail at compile time. Also, it will have a second templated member function, MyClass<U> convert<U>() const that only works if U is derived from T (or the same as T). The actual implementation of these functions is not important at this time, right now I am just trying to figure out how to declare them.

Although in some cases, it would be possible to use a static_assert with just std::is_base_of without std::enable_if to make the compile fail, but I'm wondering if I can achieve something slightly more robust using std::enable_if.

Thanks in advance

Aucun commentaire:

Enregistrer un commentaire