gpt4 book ai didi

c++ - 使用模板参数重载 operator<< 时编译错误

转载 作者:太空狗 更新时间:2023-10-29 21:46:32 26 4
gpt4 key购买 nike

我正在尝试使用 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"));
}

我正在尝试重载运算符<<。问题是代码不会编译,除非我用 namespace std 包围重载运算符 << 的定义。我认为这是由于 C++ 的名称查找机制,我仍然难以理解。即使我这样定义非模板版本:

ostream& operator<<(ostream& os, const pair<int,int>& p) {
return os << p.first << "\t" << p.second << endl;
}

它仍然无法编译。谁能解释一下为什么?

最佳答案

你的问题是 argument-dependent name lookup (日常事件能力)。编译器正在搜索 operator<< 的实现在namespace std , 作为 ostreampair在那个命名空间中。您应该制作一个转发到 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按引用而不是按值存储,你不能依赖 pair<const int, int> 的隐式转换至 pair<int, int>了。你可以改变 ostreamer按值存储,但事实上,它没有开销,我认为无论如何最好是明确的。

关于c++ - 使用模板参数重载 operator<< 时编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14948886/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com