在 child 的创建中避免构造函数重复

Avoiding constructor repetition in child's creation

我得到了一个 parent class 和多个 child class。我想根据输入动态创建不同 class 的 child objects。

假设 parent 是这样声明的:

class Parent {
public:
    Parent(int v);
};

ChildOnEChildTwo都继承了Parent。以下是否有快捷方式:

shared_ptr<Parent> myObject;
switch(input) {
    case 1: {
        myObject = make_shared<ChildOne>(int v);
        break;
    }
    case 2: {
        myObject = make_shared<ChildTwo>(int v);
        break;
    }
}

在处理两个以上的 child 时,这有点繁重,尤其是当构造函数以相同方式构造时。我们不能以某种方式复制纯虚拟构造函数的行为,以便 child 都必须实现它,然后只更改调用的 class,而不更改参数吗?

TL;DR 如何缩短 above-mentionned 示例?

您可以创建一个查找table;类似于:

using Ctor = shared_ptr<Parent>(int v);

static const std::map<int, Ctor *> ctors = {
    {1, (Ctor *)make_shared<ChildOne>}, // The cast chooses overload;
    {2, (Ctor *)make_shared<ChildTwo>}, // not sure is that necessary in such context
};

...
return (ctors.at(input))(v);

这里最棒的是虽然构造函数是特殊的并且它的地址不能被获取,make_shared是一个可以自由传递的常规函数​​指针。