c++ - 继承和显式构造函数?

标签 c++ constructor c++11 explicit-constructor

考虑以下代码:

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

最佳答案

C++11 提供 this as a feature .然而,即使是 GCC 也没有真正实现它。

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

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

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

关于c++ - 继承和显式构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11991336/

相关文章:

python - 使用现有实例初始化 super?

python - 在继承的 ctypes.Structure 类的构造函数中调用 from_buffer_copy

c++ - 移除 vector 元素使用 vector<bool> 中的条件

c++ - 如何将通用错误代码枚举与来自 <system_error> 的 system_category 错误代码一起使用?

c++ - 为什么在使用局部变量时这个带有 mov 算术的有效程序集不能编译?

c++ - STL 集的 = 运算符问题

c++ - 使用有限的 CPU 时间定期执行 pthread

c++ - 实现图形算法的正确*模式*?

c# - Nhibernate - 在构造函数中做事

c++ - 理解 C++ 字符串