【发布时间】:2014-09-19 07:44:39
【问题描述】:
我有一堆委托工厂,使用不同的参数定义为 Lambda,即:
std::function<Mesh*()> f1 = [&]() -> Mesh * {return new Mesh();};
std::function<Image*(const std::string&)> f2 = [&](const std::string& path) -> Image * {return new Image(path);};
std::function<VertexBuffer*(VertexBuffer::eType, int, int)> f3 = [&](VertexBuffer::eType type, int size, int count) -> VertexBuffer * {return new VertexBuffer(type, size, count);};
使用这些委托,我可以创建具有不同参数列表的不同对象类型。这些委托应由特定的 IOC 容器类处理,该类使用 std::type 作为键将它们存储在单个 STL 映射中,以确定应调用哪个委托。
我该如何存档?使用 std::function void 指针是不可能的,而我还需要为这些仿函数定义的参数。我也尝试为这些委托定义一个模板类作为工厂,但我没有找到解决方案,我如何为这个工厂定义一个接口,其中包含一个纯虚拟方法来调用委托。
template<class T, typename ... Args>
class DelegateFactory
{
public:
std::shared_ptr<T> create(Args&& ... args) const {
return std::shared_ptr<T>(static_cast<T*>(m_delegate(std::forward<Args>(args)...)));
}
void registerDelegate(std::function<T* (Args&& ... args)> delegate)
{
m_delegate = delegate;
}
private:
std::function<T* (Args&& ... args)> m_delegate = nullptr;
};
这看起来像是 boost::any 和 boost::any_map 的例子。但我不能使用升压。是否有一个纯基于 c++11 的解决方案来解决这个问题。或者这几乎是不可能的?
【问题讨论】:
标签: templates c++11 lambda std-function