c++ - 是否可以在运行时切换到不同的基类构造函数?

标签 c++ c++11 inheritance constructor

假设我正在编写 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/

相关文章:

python "' y'对象没有属性 'x'“调用祖 parent 方法x时

java - 调用父类(super class)构造函数

c++ - 类自身类型的静态类成员

c++ - GetCPUDescriptorHandleForHeapStart 堆栈损坏

c++ - 即使在同一类型上,是否应该使用 placement new 调用析构函数

c++ - 将 move 语义与 std::pair 或 std::tuple 一起使用

c++ - 当前面为 0 时,scanf 读取错误的整数

c++ - 找不到用户定义的整数文字

c++ - OpenMP:写入与HDF5同步的数据

java - 在 do-while 循环中使用 JSoup,仍然抛出异常