重载运算符时编译错误<<使用模板参数
Compile error when overloading operator<< with template arguments
我正在尝试使用stl-copy()来打印映射中的键值对。代码如下:
#include <iterator>
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;
//compile error if I comment out "namespace std"
namespace std {
template<typename F, typename S>
ostream& operator<<(ostream& os, const pair<F,S>& p) {
return os << p.first << "t" << p.second << endl;
}
}
int main() {
map<int, int> m;
fill_n(inserter(m, m.begin()), 10, make_pair(90,120));
copy(m.begin(), m.end(), ostream_iterator<pair<int,int> >(cout,"n"));
}
我正试图使运算符<lt;。问题是,除非我围绕重载运算符<lt;用CCD_ 1。我认为这是由于C++的名称查找机制,我仍然难以理解。即使我定义这样的非模板版本:
ostream& operator<<(ostream& os, const pair<int,int>& p) {
return os << p.first << "t" << p.second << endl;
}
它仍然无法编译。有人能解释一下原因吗?
您的问题是与参数相关的名称查找(ADL)。编译器正在namespace std
中搜索operator<<
的实现,因为ostream
和pair
都在该命名空间中。您应该制作一个包装器,从正确的名称空间转发到operator<<
:
template<class T>
struct ostreamer {
ostreamer(const T& value) : reference(value) {}
const T& reference;
friend ostream& operator<<(ostream& stream, const ostreamer& value) {
return stream << value.reference;
}
};
然后只使用ostream_iterator<ostreamer<pair<const int, int>>>
而不是ostream_iterator<pair<int, int>>
。请注意,由于ostreamer
是通过引用而不是通过值存储的,因此不能再依赖于从namespace std
0到pair<int, int>
的隐式转换。您可以将ostreamer
更改为按值存储,但实际上,它没有开销,而且我认为最好是显式的。
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 函数调用中参数的顺序重要吗
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 使用不带参数的函数访问结构元素
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 如何使用Luacneneneba API正确读取字符串和表参数
- 在派生函数中指定void*参数
- 视图中的参数推导失败:take_while
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 左角支架解释为操作员&lt;而不是模板参数
- 重载运算符<<:此运算符函数的参数太多
- 重载<<运算符错误C2804:二进制'运算符<<'参数太多