给定以下基类:
class Base {
int a, b;
public:
Base(int a, int b=42): a(a), b(b) { }
};
还有一个从基类派生的类:
class Derived: public Base {
using Base::Base; // inherit Base constructors
bool c;
public:
Derived(int a): Base(a), c(true) { }
Derived(int a, int b): Base(a, b), c(true) { }
};
有没有办法避免为 Derived
创建两个单独的构造函数而是重载继承的 Base
构造函数来初始化 Derived
的额外成员?
我想使用这样的东西:
template <typename... Args,
typename std::enable_if_t<std::is_constructible_v<Base, Args&&...>, int> = 0>
explicit Derived(Args&&... args):
Base(std::forward<Args>(args)...), c(true) {}
这很接近,但是太冗长,并且如果继承基类的构造函数则不起作用。即如果 using Base::Base
存在于类中(然后它默认为这些构造函数并且不初始化字段 b
)。
如果基类继承的构造函数不存在,即删除using Base::Base
,它就可以工作。 .
这是完成这项工作的唯一方法吗?即删除 using Base::Base
并在每个派生类中使用可变参数模板构造函数?有没有更简洁的方法来重载继承的构造函数?
我正在使用 C++17。
最佳答案
在这种情况下,您所需要做的就是为 c
提供类内初始值设定项
class Derived : public Base {
using Base::Base;
bool c = true;
};
允许您使用Base
的构造函数,并在所有情况下将c
初始化为true
。
关于c++ - 重载继承的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52706725/