title: C++ templates and object code instantiation
body: <p>With this question I'd like to better understand how C++ templates system works with regards to <a href="https://stackoverflow.com/questions/3417314/unused-template-functions-in-shared-library/">this question</a>.</p>
  
  <p>As far as I know, template-based classes and functions are usually placed into header files. This is due to the technical issue of managing generic data types, which characterstics are unknown in principle. As soon as they are known, the compiler can generate the executable code which is suited for the required data type.</p>
  
  <p>In the header file <code>something.h</code>, our class shall be defined as follows:</p>
  
  <pre><code>template &lt;typename T&gt;
  class Something
  {
      public:
          void setElement (T &amp;elem) {
              element = elem;
          }
          T getElement () {
              return element;
          }
      private:
          T element;
  };
  </code></pre>
  
  <p>Now let's suppose to split source and class definition:</p>
  
  <p>The following class definition will be written in <code>something.h</code>:</p>
  
  <pre><code>template &lt;typename T&gt;
  class Something
  {
      public:
          void setElement (T &amp;elem);
          T getElement ();
      private:
          T element;
  };
  </code></pre>
  
  <p>While the following methods will be written in <code>something.cpp</code>:</p>
  
  <pre><code>#include "something.h"
  
  template &lt;typename T&gt;
  void Something&lt;T&gt;::setElement (T &amp;elem)
  {
      element = elem;
  }
  
  template &lt;typename T&gt;
  T Something&lt;T&gt;::getElement ()
  {
      return element;
  }
  </code></pre>
  
  <p>Unless we declare some specific-type instances inside <code>something.cpp</code>, if we compile it as object file we won't obtain any text section inside it:</p>
  
  <pre><code>dacav@mithril:&lt;tmp&gt;$ g++ something.cpp  -c
  dacav@mithril:&lt;tmp&gt;$ objdump -D something.o 
  
  something.o:     file format elf64-x86-64
  
  
  Disassembly of section .comment:
  
  0000000000000000 &lt;.comment&gt;:
     0:   00 47 43                add    %al,0x43(%rdi)
     3:   43 3a 20                rex.XB cmp    (%r8),%spl
  ...
  ...
    20:   34 2e                   xor    $0x2e,%al
    22:   31 00                   xor    %eax,(%rax)
  dacav@mithril:&lt;tmp&gt;$
  </code></pre>
  
  <p><a href="https://stackoverflow.com/questions/3417314/unused-template-functions-in-shared-library/">As Martin York shows</a> we can force the compiler to generate the code for some specific data types in order to control which types can be used and which cannot. But what if we don't want any restriction?</p>