Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does inlining template specializations help and should I do it?
    text
    copied!<p>The problem with template specializations is that they're treated like normal functions because there is no template parameter used anywhere anymore. </p> <p>Therefor if the following code is put in a header file it works at first.</p> <pre><code>template &lt;typename foo&gt; void f(foo p) { std::cout &lt;&lt; "f one" &lt;&lt; std::endl; } template &lt;&gt; void f&lt;int&gt;(int p) { std::cout &lt;&lt; "f two" &lt;&lt; std::endl; } </code></pre> <p>But this stops working if the header is included in two files. In this case the error I get (with VS2010) is:</p> <pre><code>templateordering.obj : error LNK2005: "void __cdecl f&lt;int&gt;(int)" (??$f@H@@YAXH@Z) already defined in othertu.obj </code></pre> <p>And this is fixable by using the <em>inline</em> keyword as mentioned in many other questions.</p> <pre><code>template &lt;&gt; inline void f&lt;int&gt;(int p) { std::cout &lt;&lt; "f two" &lt;&lt; std::endl; } </code></pre> <p>Now this raises two questions for me:</p> <ol> <li>Is there any other way to do this? Putting the specialized function in the source file doesn't seem to work. Probably because I would need some sort of declaration in the header.</li> <li>What does inline actually do? It seems to be a common rule of thumb all over the internet that inline shouldn't be used because the compiler "will probably inline the function the way he likes in any case". So if the compiler may not inline a function that I declare as "inline", why does this work?</li> </ol>
 

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