【发布时间】:2014-02-19 21:55:28
【问题描述】:
当我在同一个 .cpp 文件中包含模板化和非模板化类时,我遇到了链接时问题。
我浏览了 C++ FAQ 35.13,35.14,35.15 并没有解决问题。
http://www.parashift.com/c++-faq-lite/separate-template-class-defn-from-decl.html
我正在使用带有 clang 的 Xcode 5。
这是一个例子
barfoo.h
class bar{
public:
void barfunc();
};
template <class T>
class foo{
public:
void foofunc();
};
这是 cpp 文件:
barfoo.cpp
void bar::barfunc(){...my code...}
template <class T>
void foo<T>::foofunc() {...my code...}
//I also put a instance of template class foo in the .cpp file
template class foo<int>;
//But is still generates the link error
错误是
clang: error: 链接器命令失败,退出代码为 1(使用 -v 查看调用)
但是当我删除栏类时,错误消失了,谁能告诉我为什么会产生这个错误?
将定义放在头文件中可以解决问题,但可能会导致另一个问题,即代码膨胀,有没有人可以提供其他解决方案?
【问题讨论】:
-
实例化没有帮助。您不能将适用于所有
T的定义放在不同的翻译单元中。 -
感谢您的快速响应,那么我应该怎么做才能避免这个错误呢?
-
如果你为所有
T定义它,它需要放在标题中或以其他方式包含在标题中(例如,标题包括底部的定义文件)。 -
也就是说,将方法
foofunc的定义也放入头部。
标签: c++ linker-errors template-classes