编写一个基于模板的工厂系统

Writing a template-based factory system

本文关键字:于模板 工厂 系统 一个      更新时间:2023-10-16

我为我正在进行的一个项目编写了一个基于模板的工厂系统

template <typename Interface, typename... Args>
void register_factory(identifier id, function<shared_ptr<Interface> (Args...)> factory);
template <typename Interface, typename... Args>
void unregister_factory(identifier id);
template <typename Interface, typename... Args>
shared_ptr<Interface> create(identifier id, Args... args);

正如您所看到的,我必须给所有的函数模板一个typename... Args参数,因为我需要访问存储工厂函数的变量:

template <typename Interface, typename... Args>
struct factory_storage {
  static map<identifier, function<shared_ptr<Interface> (Args...)> factories;
};

但从逻辑上讲,我应该只需要register_factorycreate的那些,其他地方知道Interface就足够了(同一接口的所有工厂函数都有相同的签名(。事实上,如果我使用void*而不是std::function,我就可以在代码中消除大多数typename... Args的出现。

有没有一种方法可以保持std::function的类型安全,同时避免一些混乱。我见过std::tuple用于存储typename...参数,这可能是解决我问题的一个可能方案,但它们似乎过于复杂,我希望能够避免它们。

如果std::function的签名数量是固定的,则variant(如Boost中的签名(是一个可能的解决方案。