Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You will have to define the functions inside your header file.<br> You cannot separate definition of template functions in to the source file and declarations in to header file. </p> <p>When a template is used in a way that triggers its intstantation, a compiler needs to see that particular templates definition. This is the reason templates are often defined in the header file in which they are declared. </p> <p>Reference:<br> <strong>C++03 standard, § 14.7.2.4:</strong></p> <blockquote> <p><strong>The definition</strong> of a non-exported function template, a non-exported member function template, or a non-exported member function or static data member of a class template <strong>shall be present in every translation unit</strong> in which it is explicitly instantiated.</p> </blockquote> <p><strong>EDIT:</strong><br> To clarify the discussion on the comments:<br> Technically, there are three ways to get around this linking problem:</p> <ul> <li>To move the definition to the .h file </li> <li>Add explicit instantiations in the <code>.cpp</code> file. </li> <li><code>#include</code> the <code>.cpp</code> file defining the template at the <code>.cpp</code> file using the template. </li> </ul> <p>Each of them have their pros and cons, </p> <p>Moving the defintions to header files may increase the code size(modern day compilers can avoid this) but will increase the compilation time for sure. </p> <p>Using the explicit instantiation approach is moving back on to traditional macro like approach.Another disadvantage is that it is necessary to know which template types are needed by the program. For a simple program this is easy but for complicated program this becomes difficult to determine in advance. </p> <p>While including cpp files is confusing at the same time shares the problems of both above approaches.</p> <p>I find first method the easiest to follow and implement and hence advocte using it.</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