class 模板中的友元函数和错误 LNK2019

friend function in class templates and error LNK2019

我试图在我的模板 class 中重载运算符 << 并且 我在想要

的地方出错
NSizeNatural<30> a(101);
cout << a;

没有这个整个程序编译

错误:

error LNK2019: unresolved external symbol "class   std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<<30,unsigned int,unsigned __int64,10>(class std::basic_ostream<char,struct std::char_traits<char> > &,class NSizeNatural<30,unsigned int,unsigned __int64,10> const &)" (??$?6[=12=]BO@I_K@@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@ABV?    $NSizeNatural@[=12=]BO@I_K@@@Z) referenced in function _main

我的Numbers.h文件:

template<int size, typename basic_type = unsigned int, typename long_type = unsigned long long, long_type base = bases(DEC)> 
class NSizeNatural
{
       // this is how I decelerate friend function  
     friend ostream& operator<<(ostream& str, const NSizeNatural<size, basic_type, long_type, base> & n);
}

Numbers.cpp文件中:

template<int size, typename basic_type, typename long_type, long_type base>
std::ostream& operator<<(std::ostream& out, const NSizeNatural<size, basic_type,   long_type, base> &y)
{
   // For now i want to have my code compile-able 
   return out << "gg"; 
}


我不知道如何正确地做。错误在哪里...

你的代码有两个问题,第一个是,你应该将 operator << 的实现移到头文件中(作为对你问题的评论)。

但是,第二个问题是你对 friend operator << 的定义,你必须将它定义为没有默认参数的模板函数:

template<int size, typename basic_type = unsigned int, typename long_type = unsigned long long, long_type base = bases(DEC)>
class NSizeNatural
{
    template<int size1, typename basic_type1, typename long_type1, long_type base1>
    friend ostream& operator<< (ostream& str, const NSizeNatural<size, basic_type, long_type, base> & n);
};