考虑以下程序:
#include <iostream>
#include <iterator>
#include <vector>
#include <utility>
using namespace std; //just for convenience, illustration only
typedef pair<int, int> point; //this is my specialization of pair. I call it point
istream& operator >> (istream & in, point & p)
{
return in >> p.first >> p.second;
}
int main()
{
vector<point> v((istream_iterator<point>(cin)), istream_iterator<point>());
// ^^^ ^^^
//extra parentheses lest this should be mistaken for a function declaration
}
这无法编译,因为一旦 ADL 在命名空间 std 中找到运算符 >>,它就不再考虑全局范围,无论在 std 中找到的运算符是否是可行的候选者。这是相当不方便的。如果我将运算符 >> 的声明放入命名空间 std(这在技术上是非法的),则代码可以按预期编译。除了将 point
设为我自己的类而不是将其定义为 std 命名空间中模板的特化之外,还有什么方法可以解决此问题?
提前致谢
最佳答案
添加 operator>>
的重载在 namespace std
被禁止,但有时允许添加模板特化。
但是,这里没有用户定义的类型,标准类型上的运算符也不是你可以重新定义的。专业 operator>>(istream&, pair<mytype, int>)
是合理的。
部分[namespace.std]
(n3290 的第 17.6.4.2.1 节)说
The behavior of a C++ program is undefined if it adds declarations or definitions to namespace
std
or to a namespace within namespacestd
unless otherwise specified. A program may add a template specialization for any standard library template to namespacestd
only if the declaration depends on a user-defined type and the specialization meets the standard library requirements for the original template and is not explicitly prohibited.
(强调我的)
关于c++ - 我应该在哪里为我的 std::pair 特化定义运算符 >>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6885063/