<分区>
Possible Duplicate:
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 的 undefined symbol : “std::__1::weak_ptr A::GetComponentFromName(char const*)”,引用自: _main 在 main.o 中 ld: 找不到体系结构 x86_64 的符号 clang:错误:链接器命令失败,退出代码为 1(使用 -v 查看调用)
我通过直接在头文件中定义模板方法来修复它。
我应该总是在 header 中定义模板方法吗?为什么 ? 我在 OSX 上使用 clang++ 和 XCode,如果这有任何帮助的话
谢谢