C ++模板未在头/链接器错误中定义

时间:2012-10-27 10:58:58

标签: c++ templates linker

  

可能重复:
  Why can templates only be implemented in the header file?

我刚刚遇到了一些我无法理解的事情。 在以下情况下,我在链接阶段遇到了问题。

//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" );
}

这没有编译,在链接期间我有这样的东西:

架构x86_64的未定义符号:   “std :: __ 1 :: weak_ptr A :: GetComponentFromName(char const *)”,引自:       _main在main.o中 ld:找不到架构x86_64的符号 clang:错误:链接器命令失败,退出代码为1(使用-v查看调用)

我通过直接在头文件中定义模板方法来修复它。

我应该始终在标题中定义模板方法吗?为什么? 我在OSX上并使用clang ++和XCode,如果可以提供任何帮助

由于

1 个答案:

答案 0 :(得分:1)

模板定义需要使用它对代码可见。否则将生成链接器错误。 对于这样的情况,有不同的解决方法:

Read This