1

I'm trying to overload operator << in my template class and I get error where i want to

NSizeNatural<30> a(101);
cout << a;

Without this whole program compiles

Error:

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$0BO@I_K$09@@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@ABV?    $NSizeNatural@$0BO@I_K$09@@@Z) referenced in function _main

My Numbers.h file :

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);
}

In Numbers.cpp file :

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"; 
}


I have no idea how to do it correctly. And where is a bug ...

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
Yurrili
  • 338
  • 1
  • 11
  • 1
    Short answer: you must move the implementation of `operator<<` into `Numbers.h`, so that when `main` invokes this operator, its implementation is available to the compiler. – Daniel Strul Nov 01 '15 at 13:34
  • 1
    Okay it helps with error LNK2019, so thanks. A don't how i missed it! Of course that template over operator means it's template and should be in .h file.... But now i've error 'operator <<' is ambiguous ? – Yurrili Nov 01 '15 at 13:45

1 Answers1

2

You have two problems in your code, first one is, you should move the implementation of operator << into the header file (as the comments on your question).

But, second problem is your definition of friend operator <<, you must define it as a template function without default parameter:

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);
};
masoud
  • 55,379
  • 16
  • 141
  • 208