4

I have a typedef inside a class and I would like to overload the operator<< for it to be able to print it in 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;
    k.s.insert(5);
    k.s.insert(3);
    k.DoSomething();

}

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

4

2 回答 2

4

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

于 2012-10-18T16:21:00.457 回答
0

只是为了完整性:代码的最终版本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;
}   
于 2012-10-18T16:43:39.003 回答