Note that there are some explanatory texts on larger screens.

plurals
  1. POResolving a Circular Dependency between Template Classes
    primarykey
    data
    text
    <p>I have two classes, <code>Foo&lt;T&gt;</code> and <code>Bar&lt;T&gt;</code>, derived from <code>Base</code>. Each overrides a method <code>virtual Base* convert(ID) const</code>, where <code>ID</code> is an instance of a type that uniquely identifies a particular instantiation of <code>Foo</code> or <code>Bar</code> (pretend it's an <code>enum</code>). The problem is that <code>Foo::convert()</code> needs to be able to return a <code>Bar</code> instance, and likewise <code>Bar::convert()</code> needs to be able to instantiate <code>Foo</code>. Since they're both templates, this results in a circular dependency between <code>Foo.h</code> and <code>Bar.h</code>. How do I resolve this?</p> <p><strong>Edit:</strong> A forward declaration does not work because the implementation of each method needs the constructor of the other class:</p> <p><code>Foo.h</code>:</p> <pre><code>#include &lt;Base.h&gt; template&lt;class T&gt; class Bar; template&lt;class T&gt; class Foo : public Base { ... }; template&lt;class T&gt; Base* Foo&lt;T&gt;::convert(ID id) const { if (id == BAR_INT) return new Bar&lt;int&gt;(value); // Error. ... } </code></pre> <p><code>Bar.h</code>:</p> <pre><code>#include &lt;Base.h&gt; template&lt;class T&gt; class Foo; template&lt;class T&gt; class Bar : public Base { ... }; template&lt;class T&gt; Base* Bar&lt;T&gt;::convert(ID id) const { if (id == FOO_FLOAT) return new Foo&lt;float&gt;(value); // Error. ... } </code></pre> <p>The error is, naturally, "invalid use of incomplete type".</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload