2017-04-08 66 views
0

我在连接下面的一段代码时遇到了问题。链接器找不到朋友模板函数的实现。 任何想法为什么它找不到它?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

+0

[为什么模板仅可在头文件执行?](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) –

回答

0

没有运营商< <定义当你定义XY和使用运营商< <。您可以在源文件中定义一个模板,但是不会为uint16_t实例化此模板。您可以通过在源文件末尾显式模板实例化来绕过。

template std::ostream& operator<< <uint16_t> (std::ostream& os, const XY<uint16_t>& rhs);

但我认为这不是一个好主意。你最好在头文件中声明和定义模板。

+0

的确,谢谢你们 – user3124812

相关问题