C++ Template : one list by class, how to factorize the code?
<p>Suppose I have this class :</p>

<pre><code>class Component1;
class Component2;
// many different Components
class Component42;

class MyClass
{
public:
    MyClass(void) {};
    std::list&lt;Component1&gt; component1List;
    std::list&lt;Component2&gt; component2List;
    // one list by component
    std::list&lt;Component42&gt; component42List;
};
</code></pre>

<p>I would like to create a function with the following signature:</p>

<pre><code>template&lt;class T&gt; void addElement(T component);
</code></pre>

<p>It should do the following:</p>

<ul>
<li>if <code>component</code> is of type <code>Component1</code>, add it to <code>Component1List</code></li>
<li>if <code>component</code> is of type <code>Component2</code>, add it to <code>Component2List</code>, etc.</li>
</ul>

<p>Is it possible? What's a good way to do this?</p>

<p>I can obtain the same behaviour with a function like :</p>

<pre><code>template&lt;class T&gt; void addElement(int componentType, T component);
</code></pre>

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