关于继承:C ++根据运行时值选择要使用的虚拟基类的实现

C++ pick which implementation of virtual base class to use based on runtime value

我有一个C ++纯虚拟基类/接口,它具有几个在代码中不同位置定义的实现,以后可能会添加其他实现。 我需要一种方法来注册可用的实现,(从配置文件,用户输入等中)读取要使用的接口的实现,然后构造该实现的实例。

如何以一般方式(即表驱动,而不使用显式列出每个实现的switch / case语句)执行此操作? 我在弄清楚如何从指示类型的运行时值转换为可以实例化的编译时类型时遇到麻烦。

Boost有这样的东西吗?


标准方法涉及一种称为工厂的创建模式,该模式根据用户提供的标识符实例化具体类型。

如果您已经在使用Boost,请查看Boost.Functional / Factory,但是自己构建基于表的调度机制并不是很困难。 这是将Boost版本与运行时多态一起使用的方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
struct abstract
{
    virtual ~abstract() = default;
    virtual void f() = 0;
};

struct concrete1 : abstract
{
    virutal void f() override;
};

struct concrete2 : abstract
{
    virutal void f() override;
};

typedef boost::function  abstract_factory;

int main()
{
    // Here, each factory refers to a function, although sometimes
    // people use the term factory to mean the dispatch table itself.
    std::map<std::string, abstract_factory> factories;
    factories["foo"] = boost::factory<concrete1*>();
    factories["bar"] = boost::factory<concrete2*>();

    // Create a new concrete object.
    auto foo = factories["foo"]();

    // vtable dispatch"concrete1".
    foo->f();

    ...
}