【发布时间】:2014-06-08 21:18:13
【问题描述】:
这个程序
// main.cpp
#include <iostream>
#include <utility>
#include <algorithm>
#include <iterator>
#include <map>
template<typename t1, typename t2>
std::ostream& operator<<(std::ostream& os, const std::pair<t1, t2>& pair)
{
return os << "< " << pair.first << " , " << pair.second << " >";
}
int main()
{
std::map<int, int> map = { { 1, 2 }, { 2, 3 } };
std::cout << *map.begin() << std::endl;//This works
std::copy(
map.begin(),
map.end(),
std::ostream_iterator<std::pair<int,int> >(std::cout, " ")
); //this doesn't work
}
产生错误
no match for ‘operator<<’ (operand types are ‘std::ostream_iterator<std::pair<int, int> >::ostream_type {aka std::basic_ostream<char>}’ and ‘const std::pair<int, int>’)
我猜这不起作用,因为我的重载在 std::copy 中不可用,但这是为什么呢?
【问题讨论】:
-
我不知道为什么人们不赞成这个问题,它的意图很明确,尽管标题可以写得更好。
-
@Filip Roséen - refp 论坛里有很多白痴喜欢投反对票。问题在于,在第二种情况下,当实例化模板类 std::ostream_iterator. 时,在命名空间 std:: 中搜索适当的运算符函数。由于命名空间 std 中已经声明了运算符
-
@VladfromMoscow 这不是的答案;我正在做一个详细的描述。有空时我会联系你和克里斯。
-
@Filip Roséen - refp 请参阅模板实例化和名称搜索部分。
-
@VladfromMoscow 我会让你在有空的时候阅读我的答案。