我为我正在进行的项目编写了一个基于模板的工厂系统。这些是我所拥有的一些功能模板的签名:
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_factory
和create
的那些,知道Interface
应该足够的其他地方(同一个接口的所有工厂函数都具有相同的签名)。事实上,如果我使用void*
代替std::function
,我可以在代码中删除大多数typename... Args
。
有没有办法可以保持std::function
的类型安全性并避免一些混乱。我已经看到std::tuple
用于存储typename...
个参数,这些可能是解决我问题的一种方法,但它们似乎过于复杂,我希望能够避免它们