我在连接下面的一段代码时遇到了问题。链接器找不到朋友模板函数的实现。 任何想法为什么它找不到它?operator << in template class;与命名空间;
宣言
// XY.hpp
namespace xxx
{
template<typename T> class XY;
template<typename T>
std::ostream& operator<<(std::ostream&, const XY<T>&);
template<typename T>
class XY
{
public:
// ... constructors, destructor, getters, setters, etc
friend std::ostream& operator<< <T>(std::ostream&, const XY<T>&);
private:
//...
};
} /* namespace xxx*/
定义
// XY.cpp
#include "XY.hpp"
namespace xxx
{
template<typename T>
std::ostream& operator<<(std::ostream& os, const XY<T>& rhs)
{
// ...
return os;
}
} /* namespace xxx */
使用
// main.cpp
#include "XY.hpp"
#include <iostream>
using namespace std;
using namespace xxx;
int main() {
XY<uint16_t> xy;
cout << xy;
return 0;
}
链接返回错误:undefined reference to 'std::ostream& xxx::operator<< <unsigned short>(std::ostream&, xxx::XY<unsigned short> const&)'
与链接
版本:gcc.EXE (GCC) 6.3.0
[为什么模板仅可在头文件执行?](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) –