title: Templated list of templated objects in C++
body: <p>I'm trying to create a list of objects, where each object also stores 'ownership' - ie, it knows which list holds it.</p>
  
  <p>In a non-template situation, it's straightforward:</p>
  
  <pre><code>class FooList;  // forward declaration
  
  class FooItem
  {
    public:
       FooList *owner;
    ...
  };
  
  class FooList: private std::list&lt;FooItem&gt;
  {
    ...
  };
  </code></pre>
  
  <p>However, the list class is a template, based on the contained object type, and I'm struggling to work out how to specify this. I reckon the FooItem class now needs to be a template because the type of 'owner' can vary:</p>
  
  <pre><code>template &lt;class E&gt; class FooItem
  {
    public:
       std::list&lt;E&gt; *owner;
  };
  
  template &lt;class E&gt; class FooList: private std::list&lt;E&gt;
  {
    ...
  };
  </code></pre>
  
  <p>But, now given my two templates, how can I define the new types I want? The snippet below is what I think I need, but it gives <code>"error: Multiple declaration for BarItem"</code>.</p>
  
  <pre><code>class BarItem;
  
  typedef FooList&lt;BarItem&gt; BarList;
  typedef FooItem&lt;BarList&gt; BarItem;
  </code></pre>
  
  <hr>
  
  <p><strong>EDIT:</strong></p>
  
  <p>Thanks to those who pointed out the issue of <code>std::list&lt;E&gt;</code> instead of <code>std::list&lt;FooItem&lt;E&gt; &gt;</code></p>
  
  <hr>
  
  <p><strong>EDIT 2:</strong>
  Renamed classes to <code>Base, Derived, BaseList, DerivedList.</code></p>
  
  <p>My real problem was the 'circular typedef'. After some more tinkering, I think this will do what I require. It creates a 'real' BarItem class rather than just a typedef, but seems to at least compile now.</p>
  
  <pre><code>template &lt;class E&gt; class BaseList; // forward declaration
  
  template &lt;class E&gt; class Base
  {
    public:
       BaseList&lt; Base&lt;E&gt; &gt; *owner;
  };
  
  template &lt;class E&gt; class BaseList: private std::list&lt; E &gt;
  {
  };
  
  // typedef Base&lt;BaseList&lt;Derived&gt; &gt; Derived;  //This won't compile, unsurprisingly.
  
  class Derived : public Base &lt; BaseList&lt;Derived&gt; &gt;  // Surprisingly, this seems to.
  {
  ...
  };
  
  typedef BaseList&lt;Derived&gt; DerivedList;
  </code></pre>
  
  <p>Does this seem to make sense? Is it a common idiom or something horrible?</p>