Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I have two quick tips that may save you some problems in the future.</p> <p><strong>Templates must be defined and implemented in headers, because they are translated/created at compile-time</strong></p> <p>If you have the following code:</p> <pre><code>// Foo.h template &lt;typename T&gt; class Foo { ... }; // Bar.cpp #include "Foo.h" void func() { Foo&lt;int&gt; fooInt; Foo&lt;double&gt; fooDouble; } </code></pre> <p>When processing the Bar.cpp file, the compiler will "create" a new definition of the Foo class with every T replaced with the int type for the fooInt instance, and a new definition of the Foo class with every T replaced with the double type for the fooDouble instance.</p> <p>In a nutshell, C++ does not support template classes, the compiler emulates them replacing the types at compile time and creating normal classes. So, the compiled type of fooInt and fooDouble are different.</p> <p>Because they are translated at compile-time and not compiled individually, they <em>must</em> be defined and implemented in headers.</p> <p>If you implement the template class as a normal class (header and source file) the error thrown by the compiler (the linker actually) is that there is no method implemented (it's because the source file is ignored).</p> <p><strong>You can still create forward declarations to avoid cyclic dependencies</strong></p> <p>It's just that you have to forward declare them like this:</p> <pre><code>template &lt;typename T&gt; class Foo; </code></pre> <p>And, as with normal forward declarations, you have to be sure that you are including all the headers necessary.</p>
 

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