开发者

A collection of template objects with different template parameters

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜