Overloading << for a type inside another class

I have a typedef inside a class and I would like to overload operator<< so that it can print it to ostream . However, the compiler cannot find the overloaded operator. How can I declare it so that it works?

 #include <iostream> #include <set> using namespace std; template <class C> struct K { typedef std::set<C> Cset; Cset s; // and many more elements here friend ostream& operator<<(ostream& oo, const Cset& ss){ typename Cset::const_iterator it=ss.begin(); oo << "["; for(; it!=ss.end(); ++it) oo << (*it) << ","; oo << "]"; return oo; } void DoSomething(){ // do something complicated here cout << s << endl; // do something complicated here } }; int main(){ K <int> k; ksinsert(5); ksinsert(3); k.DoSomething(); } 

gcc version 4.4.5 20101112 (Red Hat 4.4.5-2) (GCC)

+4
source share
2 answers

When the friend function is defined inline , and there is no forward declaration in front of the class, it is found only in ADL . However, your overload will never be found using ADL , since it does not include K arguments (note that K<int>::CSet is a typedef for std::set<C> ).

+4
source

For completeness only: the final version of the code for operator<< :

 template <class T, class U> std::ostream& operator<<(std::ostream& oo, const std::set <T,U> & ss){ typename std::set <T,U> ::const_iterator it=ss.begin(); oo << "["; if(it!=ss.end()) oo << (*it++); while(it!=ss.end()) oo << "," << (*it++); oo << "]"; return oo; } 
0
source

Source: https://habr.com/ru/post/1440592/


All Articles