假设我正在编写 Derived
并且必须从 Base
继承,我不控制它并且有两个独立的构造函数和一个删除的复制和移动构造函数:
struct Base {
Base(int i);
Base(const char *sz);
Base(const Base&) = delete;
Base(const Base&&) = delete;
};
struct Derived {
Derived(bool init_with_string);
};
现在,根据 another_param
的值,我必须使用构造函数或其他构造函数来初始化我的基类;如果 C++ 不那么严格,它会是这样的:
Derived::Derived(bool init_with_string) {
if(init_with_string) {
Base::Base("forty-two");
} else {
Base::Base(42);
}
}
(这对于计算传递给直接表达式中的基类构造函数/字段初始化器的值很麻烦的所有情况也很有用,但我跑题了)
不幸的是,即使我没有看到这种事情的特定代码生成或对象模型障碍,这也不是有效的 C++,我也想不出简单的解决方法。
有什么我不知道的解决方法吗?
最佳答案
静态函数在这里可以正常工作
struct Base {
Base(int i);
Base(const char *sz);
Base(const Base&) = delete;
Base(const Base&&) = delete;
};
struct Derived : Base {
using Base::Base;
static Derived construct(bool with_string) {
if(with_string) return { "forty-two" };
return { 42 };
}
};
请注意,这不需要移动,也不需要复制构造函数。如果你想把它作为本地,你需要将它绑定(bind)到一个引用以避免移动它
auto &&w = Derived::construct(true);
auto &&wo = Derived::construct(false);
关于c++ - 是否可以在运行时切换到不同的基类构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43681029/