0

Possible Duplicate:
Why can templates only be implemented in the header file?

I just came across something that I failed to understand. I had a problem at the linking stage in the following case.

//header file
class A 
{
    template<class T>
    std::weak_ptr<T> GetSomethingFromSomeWhere(const char* Id);
};

//cpp file
template<class T>
std::weak_ptr<T> 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<B>( "id" );
}

This didn't compile, during linking I have something of this kind :

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)

I fixed it by defining the template method directly in the header file.

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

Thanks

Community
  • 1
  • 1
lollancf37
  • 1,105
  • 3
  • 15
  • 27

1 Answers1

1

Template definition needs to be visible to the code using it. Otherwise linker errors will be generated. There are different workarounds for situations like that:

Read This

sgarizvi
  • 16,623
  • 9
  • 64
  • 98