【发布时间】: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_factory 和create 的那些,在其他任何地方知道Interface 就足够了(同一接口的所有工厂函数都具有相同的签名)。事实上,如果我使用 void* 而不是 std::function,我可以在我的代码中去掉大部分出现的 typename... Args。
有没有一种方法可以保持std::function 的类型安全并避免一些混乱。我已经看到 std::tuple 用于存储 typename... 参数,这些可能是解决我的问题的一种可能方法,但它们似乎过于复杂,我希望能够避免它们。
【问题讨论】:
-
This may be related,我用它解决了类似的问题。
-
由于用户必须记住
id和Args类型之间的匹配,返回一个基于Interface和Args的模板类ID而不是简单的@987654338是否有意义@ ? -
无论如何我都需要创建一个
std::function<Interface>(Args...)函数类型。如果我没有收到 Interface 和 Args 作为模板参数,我该如何构造该类型? -
@Elektito:我的意思是如果
id类似于identifier<Interface, Args...>,那么您想要的模板参数可以从id推导出来。 -
这可能是可能的,但
identifier这里是一个 int typedef,在整个代码中广泛用于各种目的。我需要更改很多代码才能做到这一点。
标签: c++ templates c++11 factory