我有一个C ++纯虚基类/接口,有几个实现,它们在代码的不同位置定义,其他实现可能会在以后添加。我需要一种方法来注册可用的实现,读入(从配置文件,用户输入等)要使用的接口的实现,然后构造该实现的实例。
如何以一般方式执行此操作(即,表驱动,而不是使用明确列出每个实现的switch / case语句)?我无法确定如何从指示类型的运行时值转到我可以实例化的编译时类型。
boost有没有这样的东西?
答案 0 :(得分:1)
标准方法涉及一个名为creational的pattern factory,它根据用户提供的标识符实例化具体类型。
如果您已经在使用Boost,请查看Boost.Functional/Factory,但构建基于表的调度机制yourself并不是很困难。这就是你如何使用带有运行时多态性的Boost版本:
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*()> 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();
...
}