gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:24:30 24 4
gpt4 key购买 nike

考虑以下代码:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com