4

考虑以下代码:

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
};

有没有办法重新设计这段代码,Derived使所有的构造函数都Base具有相同的显式/隐式属性?

4

2 回答 2

6

C++11将其作为一个特性提供。然而,甚至 GCC 还没有真正实现它。

当它实际实现时,它看起来像这样:

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

话虽如此,它可能对您的情况没有帮助。继承的构造函数是一个全有或全无的命题。你得到所有的基类构造函数,完全使用它们的参数。另外,如果你定义一个与继承的具有相同签名的构造函数,你会得到一个编译错误。

于 2012-08-16T16:13:41.423 回答
2

To detect implicit/explicit constructibility 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 implicit convertibility and use std::is_constructible to check explicit convertibility in addition.

Edit: fixed enable_if template parameters using solution from boost::enable_if not in function signature.

Checks:

Derived<int>{5};                            // allowed
[](Derived<int>){}(5);                      // allowed
Derived<int>{std::string{"hello"}};         // allowed
[](Derived<int>){}(std::string{"hello"});   // not allowed
于 2012-08-16T16:51:04.087 回答