Mr. Boy
Mr. Boy

Reputation: 63748

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.

Upvotes: 2

Views: 654

Answers (1)

Puppy
Puppy

Reputation: 146940

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.

Upvotes: 1

Related Questions