Inheritance and explicit constructors?

Consider the following code:

template<typename T> class Base { Base(); Base(const Base<T>& rhs); template<typename T0> explicit Base(const Base<T0>& rhs); template<typename T0, class = typename std::enable_if<std::is_fundamental<T0>::value>::type> Base(const T0& rhs); explicit Base(const std::string& rhs); }; template<typename T> class Derived : Base<T> { Derived(); Derived(const Derived<T>& rhs); template<class T0> Derived(const T0& rhs) : Base(rhs); // Is there a way to "inherit" the explicit property ? // Derived(double) will call an implicit constructor of Base // Derived(std::string) will call an explicit constructor of Base }; 

Is there a way to reverse engineer this code so that Derived will have all Base constructors with the same explicit / implicit properties?

+4
source share
2 answers

C ++ 11 offers this feature . However, even GCC does not actually implement it.

When it is implemented, it will look like this:

 template<typename T> class Derived : Base<T> { using Base<T>::Base; }; 

Speaking, this may not help your case. Inherited constructors are an all-or-nothing sentence. You get all the base class constructors, using exactly their parameters. Also, if you define a constructor with the same signature as the inherited one, you get a compilation error.

+6
source

To discover implicit / explicit constructivity for SFINAE:

 template<class T0, typename std::enable_if< std::is_convertible<const T0 &, Base<T>>::value, int>::type = 0> Derived(const T0& rhs) : Base<T>(rhs) { } template<class T0, typename std::enable_if< std::is_constructible<Base<T>, const T0 &>::value && !std::is_convertible<const T0 &, Base<T>>::value, int>::type = 0> explicit Derived(const T0& rhs) : Base<T>(rhs) { } 

Use the fact that std::is_convertible checks for implicit convertibility and uses std::is_constructible to further check for explicit convertibility.

Edit: the parameters of the enable_if template are fixed using a solution from boost :: enable_if, and not in the function signature .

Verification:

 Derived<int>{5}; // allowed [](Derived<int>){}(5); // allowed Derived<int>{std::string{"hello"}}; // allowed [](Derived<int>){}(std::string{"hello"}); // not allowed 
+2
source

All Articles