为什么ostream_iterator不能按预期工作? [英] Why does ostream_iterator not work as expected?
问题描述
不必多说下面的代码:
#include <utility>
#include <vector>
#include <iostream>
#include <iterator>
using namespace std;
typedef pair<char, char> PAIR;
ostream& operator <<(ostream& os, const PAIR& r)
{
return os << r.first;
}
int main()
{
vector<PAIR> coll;
cout << coll[0]; // OK.
// The following line will cause a compilation error! Why???
copy(coll.begin(), coll.end(), ostream_iterator<PAIR>(cout));
}
推荐答案
问题是,查找找不到运算符<<(ostream& os,const PAIR& r)
。试图调用运算符<
的代码位于 ostream_iterator<>
std
命名空间。名称查找查找 ostream_iterator<>
和 std
命名空间中的正确函数;因为这两个参数都在 std
命名空间中。
The problem is that the name lookup does not find your operator<<(ostream& os, const PAIR& r)
. The code that tries to invoke the operator<<
is in somewhere inside the ostream_iterator<>
which is itself inside the std
namespace. The name lookup looks around for the right function inside ostream_iterator<>
and the std
namespace; the argument dependent lookup does not help here because both of the parameters are in the std
namespace, too.
,我的建议是(1)将你的操作符包装到命名空间std {}
,但那是UB,IIRC。或者(2)创建一个继承自 std :: pair
的结构,以在命名空间中定义一个新类型,并使用ADL找到 <()
。
So, my suggestion is (1) either to wrap your operator into namespace std { }
, but that is UB, IIRC. Or (2) create a struct inheriting from std::pair
to define a new type in your namespace, and using the ADL to find your operator<<()
.
UPDATE:
我的第三个建议是使用自定义的操纵器打印出一对。
My 3rd suggestion is to use a custom manipulator to print out the pair.
至于我的第二个建议,如果你可以使用C ++ 11,继承自 std :: pair
应该很容易(未测试):
As for my 2nd suggestion, if you can use C++11, inheriting from std::pair
should be easy (untested):
struct PAIR : std::pair
{
using std::pair::pair;
};
如果你不能使用C ++ 11,那么我建议使用自定义的操纵器。
If you cannot use C++11, then I suggest using a custom manipulator.
这篇关于为什么ostream_iterator不能按预期工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!