编写一个基于模板的工厂系统
Writing a template-based factory system
我为我正在进行的一个项目编写了一个基于模板的工厂系统
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...
参数,这可能是解决我问题的一个可能方案,但它们似乎过于复杂,我希望能够避免它们。
如果std::function
的签名数量是固定的,则variant
(如Boost中的签名(是一个可能的解决方案。
相关文章:
- 使用模板参数重载C++方法:如何使其适用于模板的子类?
- 类成员函数参数列表是否可以依赖于模板参数?
- 依赖于模板的错误
- 将 c++ 类成员函数专用于模板类
- C++ 使函数调用依赖于模板参数
- 可变参数模板 工厂使用 std::bind 和 std::p laceholders
- c ++如何将模板应用于模板类的孩子/朋友?
- 如何修复"没有依赖于模板参数的参数'glGenVertexArrays'......"C++ 中的错误
- 如何转发声明依赖于变量定义的类,而变体定义又依赖于模板化类?
- 动态强制转换适用于模板成员函数内的共享指针和弱指针,无需代码重复
- 如何确保 "<<" 运算符适用于模板化 ADT 定义中的任何泛型类型?
- 将 const 限定符应用于模板参数时的不同编译器行为
- 如何定义依赖于模板参数的类型定义
- 如何使用类型专用化模板方法,该类型本身就是一个模板,其中只有返回类型依赖于模板类型
- PHP 相当于C++模板
- 仅专用于模板类的一个方法(部分)
- 依赖于模板的实现
- C++ 错误:"没有依赖于模板参数的'setw'参数
- 依赖于模板参数的范围查找
- 对应于模板中的定义的声明