Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It is <em>not</em> necessary to put the implementation in the header file, see the alternative solution at the end of this answer.</p> <p>Anyway, the reason your code is failing is that, when instantiating a template, the compiler creates a new class with the given template argument. For example:</p> <pre><code>template&lt;typename T&gt; struct Foo { T bar; void doSomething(T param) {/* do stuff using T */} }; // somewhere in a .cpp Foo&lt;int&gt; f; </code></pre> <p>When reading this line, the compiler will create a new class (let's call it <code>FooInt</code>), which is equivalent to the following:</p> <pre><code>struct FooInt { int bar; void doSomething(int param) {/* do stuff using int */} } </code></pre> <p>Consequently, the compiler needs to have access to the implementation of the methods, to instantiate them with the template argument (in this case <code>int</code>). If these implementations were not in the header, they wouldn't be accessible, and therefore the compiler wouldn't be able to instantiate the template.</p> <p>A common solution to this is to write the template declaration in a header file, then implement the class in an implementation file (for example .tpp), and include this implementation file at the end of the header.</p> <pre><code>// Foo.h template &lt;typename T&gt; struct Foo { void doSomething(T param); }; #include "Foo.tpp" // Foo.tpp template &lt;typename T&gt; void Foo&lt;T&gt;::doSomething(T param) { //implementation } </code></pre> <p>This way, implementation is still separated from declaration, but is accessible to the compiler.</p> <p>Another solution is to keep the implementation separated, and explicitly instantiate all the template instances you'll need:</p> <pre><code>// Foo.h // no implementation template &lt;typename T&gt; struct Foo { ... }; //---------------------------------------- // Foo.cpp // implementation of Foo's methods // explicit instantiations template class Foo&lt;int&gt;; template class Foo&lt;float&gt;; // You will only be able to use Foo with int or float </code></pre> <p>If my explanation isn't clear enough, you can have a look at the <a href="https://isocpp.org/wiki/faq/templates#templates-defn-vs-decl" rel="noreferrer">C++ Super-FAQ on this subject</a>.</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