title: C++ templates not defined in header / linker error
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file">Why can templates only be implemented in the header file?</a>  </p>
  </blockquote>
  
  
  
  <p>I just came across something that I failed to understand.
  I had a problem at the linking stage in the following case.</p>
  
  <pre><code>//header file
  class A 
  {
      template&lt;class T&gt;
      std::weak_ptr&lt;T&gt; GetSomethingFromSomeWhere(const char* Id);
  };
  
  //cpp file
  template&lt;class T&gt;
  std::weak_ptr&lt;T&gt; A:GetSomethingFromSomeWhere(const char* id)
  {
     //A method with the right stuff inside and the right return statement
     ...
  }
  
  
  //Another class
  class B
  {
  };
  
  //main.cpp
  int main ()
  {
     A a;
     auto pB = a.GetSomethingFromSomeWhere&lt;B&gt;( "id" );
  }
  </code></pre>
  
  <p>This didn't compile, during linking I have something of this kind :</p>
  
  <p>Undefined symbols for architecture x86_64:
    "std::__1::weak_ptr A::GetComponentFromName(char const*)", referenced from:
        _main in main.o
  ld: symbol(s) not found for architecture x86_64
  clang: error: linker command failed with exit code 1 (use -v to see invocation)</p>
  
  <p>I fixed it by defining the template method directly in the header file.</p>
  
  <p>Should I always define template method in the header ? Why ?
  I am on OSX and use clang++ with XCode if that can be of any help</p>
  
  <p>Thanks</p>