重载另一个类中的类型的<<
Overloading << for type inside another class
我在类中有一个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.520101112 (Red Hat 4.4.5-2) (GCC)
当friend
函数被定义inline
并且类外没有前向声明时,它只能由ADL
找到。但是,ADL
永远不会找到您的重载,因为它不涉及K
参数(请注意,K<int>::CSet
是std::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;
}
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 运行同一解决方案的另一个项目的项目
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- C++从另一个类访问公共静态向量的正确方法是什么
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 使用std::transform将一个范围的元素添加到另一个范围中
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 我可以将一个用clang c++11编译的对象与另一个用c++17编译的对象链接起来吗
- 修改函数中的指针(将另一个指针作为参数传递)
- 为什么我不能将一个对象push_back到属于另一个类的对象向量中?
- C++试图读取一个文件并输出到另一个文本文件
- 如何将指针从一个void函数传递到另一个C++
- 如何从另一个文件继承私有成员变量和公共函数
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- C++-我可以创建另一个类的成员并在构造函数中使用它吗
- 如何在C++中将函数发送到另一个进程
- 如何过载<<用于YAML::Emitter的运算符,以序列化包含另一个自定义类的向量的自定义类