lundi 4 janvier 2016

C++ Template : one list by class, how to factorize the code?

Suppose I have this class :

class Component1;
class Component2;
// many different Components
class Component42;

class MyClass
{
public:
    MyClass(void) {};
    std::list<Component1> component1List;
    std::list<Component2> component2List;
    // one list by component
    std::list<Component2> component42List;
};

I would like to create a function with signature

template<class T> void addElement(T component);

And does the following :

  • if component is of type Component1, add it to Component1List
  • if component is of type Component2, add it to Component2List, etc.

Is it possible? What's a good way to do this?

I can obtain the same behaviour with a function like :

template<class T> void addElement(int componentType, T component);

but I'd rather not have to specify the componentType like this : it's useless information and it open the door to possible errors (if componentType doesn't represent the type of component).

Thanks for your help

Aucun commentaire:

Enregistrer un commentaire