【问题标题】:Writing a template-based factory system编写基于模板的工厂系统
【发布时间】:2014-05-25 06:49:14
【问题描述】:

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

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

【问题讨论】:

  • This may be related,我用它解决了类似的问题。
  • 由于用户必须记住idArgs类型之间的匹配,返回一个基于InterfaceArgs的模板类ID而不是简单的@987654338是否有意义@ ?
  • 无论如何我都需要创建一个std::function&lt;Interface&gt;(Args...) 函数类型。如果我没有收到 Interface 和 Args 作为模板参数,我该如何构造该类型?
  • @Elektito:我的意思是如果id 类似于identifier&lt;Interface, Args...&gt;,那么您想要的模板参数可以从id 推导出来。
  • 这可能是可能的,但identifier 这里是一个 int typedef,在整个代码中广泛用于各种目的。我需要更改很多代码才能做到这一点。

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


【解决方案1】:

如果std::function的签名数量是固定的,variant(与Boost一样)是一种可能的解决方案。

【讨论】:

  • 恐怕不是这样的。这是一个库,我无法控制以后如何使用它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多