具有不同模板参数的模板对象的集合
作为一种工厂方法设置,我想注册函子,每个函子创建不同类型的对象,但满足通用接口 - 即所有创建子类化核心类的对象。
假设我有类似的内容:
template <class T> struct FactoryMethod
{
X* create();
}
我不能拥有 (IIRC) std::map
因为每个 FactoryMethod
模板专业化都是一个单独的类型。但我可以做:
struct IFactoryMethod
{
virtual X* create()=0;
};
template <class T> struct FactoryMethod : public IFactoryMethod
{
virtual X* create();
};
std::map<std::string,IFactoryMethod*> factories;
对吗?我不知道标准 STL 有办法让这个变得更整洁,尽管我猜 boost 确实如此 - 但是我们现在不使用 boost,无论如何我都很感兴趣。
这个想法是,然后可以根据类型名称(例如从 XML 读取)查找工厂来创建正确的类型。
As a kind of factory-method setup I want to register functors which each create objects of a different type, but meet a common interface - i.e all create objects subclassing a core class.
Say I have something like:
template <class T> struct FactoryMethod
{
X* create();
}
I cannot have (IIRC) std::map<std::string,FactoryMethod*>
because each FactoryMethod
template specialization is a separate type. But I could do:
struct IFactoryMethod
{
virtual X* create()=0;
};
template <class T> struct FactoryMethod : public IFactoryMethod
{
virtual X* create();
};
std::map<std::string,IFactoryMethod*> factories;
Right? I am not aware standard STL has a way to make this neater though I guess boost does - however we don't use boost right now and I am interested anyway.
The idea is then factories
can be looked up based on type-name (read from XML for instance) to create the right type.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这称为类型擦除,是一个相当常见的习惯用法 - 尽管您的映射当然可以由所有权强制指针组成,并且您也可以像大多数理智的人一样使用虚拟析构函数。
This is known as type erasure and is a fairly common idiom- although your map could of course be made of ownership-enforcing pointers and you could also use a virtual destructor like most sane people.