编写基于模板的工厂系统

时间:2014-05-25 06:49:15

标签: c++ templates c++11 factory

我为我正在进行的项目编写了一个基于模板的工厂系统。这些是我所拥有的一些功能模板的签名:

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...个参数,这些可能是解决我问题的一种方法,但它们似乎过于复杂,我希望能够避免它们

1 个答案:

答案 0 :(得分:1)

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