title: Why do I sometimes need to put c++ template function definitions in header file?
body: <p>So I was getting a linking error in my c++ project and a stackoverflow post mentioned that template methods need to also be defined in the header instead of the source file.</p>
  
  <p>The code for that specific method is (after combinging the declaration / definition):</p>
  
  <pre><code>struct Timer {
    template &lt;typename T&gt;
    const long getDuration() const; 
  };
  
  template &lt;typename T&gt;
  const long Timer::getDuration() const {
     long time = static_cast&lt;long&gt;(std::chrono::duration_cast&lt;T&gt;(end - start).count());
  
    return time &gt; 0 ? time : 1L;
  }
  </code></pre>
  
  <p>Now the explaination was that for templates, the compiler needed the definition in order to be able to process it but that does not seem to be the case all the time.</p>
  
  <p>For example, this is code that to me looks similar as the code above however I can place the declaration in the header file and the definition in source file:</p>
  
  <pre><code>// Enity.hpp
  class Entity {
    public:
      template &lt;typename T&gt;
      bool hasComponent() const;
  }
  
  // Entity.cpp
  template &lt;typename T&gt;
  bool Entity::hasComponent() const {
    return componentBitSet[getComponentTypeId&lt;T&gt;()];
  }
  </code></pre>
  
  <p>I am still relatively new to modern c++ so I am trying to understand why in the first example I need the declaration and definition in the same file and in the second, they can be split out.</p>