重载另一个类中的类型的<<

Overloading << for type inside another class

本文关键字:lt 另一个 类型 重载      更新时间:2023-10-16

我在类中有一个typedef,我想重载operator<<,以便它能够以ostream打印它。但是,编译器找不到重载运算符。如何声明它以使其正常工作?

#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 版本 4.4.5

20101112 (Red Hat 4.4.5-2) (GCC)

friend函数被定义inline并且类外没有前向声明时,它只能由ADL找到。但是,ADL永远不会找到您的重载,因为它不涉及K参数(请注意,K<int>::CSetstd::set<C>typedef)。

只是为了完整起见: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;
}   
相关文章: