Note that there are some explanatory texts on larger screens.

plurals
  1. POFixing order of inclusion when there is circular dependency in C++ template classes
    text
    copied!<p>I came across a circular dependency issue, where the order of inclusion of headers matters. <a href="https://stackoverflow.com/questions/3353831/resolving-a-circular-dependency-between-template-classes">This</a> problem is similar, but it does not document the solution where one class instantiates an object of the other. </p> <p><strong>Problem:</strong> </p> <ul> <li>I have two classes: Foo and Bar. Bar is templatized. (Foo may or may not be templatized). </li> <li>Foo has an instance of Bar, and Bar has a pointer of type Foo, and the implementation of Bar needs to access members of Foo through this pointer. </li> <li>Foo and Bar have to be implemented <strong>within separate files</strong>. As Bar is templatized, its declaration and implementation have to be in the same file.</li> </ul> <p>In the following code, if main.cpp includes Bar.h before Foo.h the code compiles, and does not when Foo.h is included before Bar.h. <em>Is there a way to make the code compile, irrespective of the order in which headers are included in main.cpp?</em></p> <p><strong>Foo.h</strong></p> <pre><code>#ifndef FOO_H #define FOO_H #include"Bar.h" class Foo { public: Bar&lt;&gt; B; void fooStuff(){}; }; #endif </code></pre> <p><strong>Bar.h</strong></p> <pre><code>#ifndef BAR_H #define BAR_H class Foo; template&lt;int N=0&gt; class Bar { public: Foo * F; void barStuff(); }; #include"Foo.h" template&lt;int N&gt; void Bar&lt;N&gt;::barStuff() { F-&gt;fooStuff(); }; #endif </code></pre> <p><strong>main.cpp</strong></p> <pre><code>#include"Foo.h" #include"Bar.h" int main() { Foo F; F.B.barStuff(); }; </code></pre>
 

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