c++ - 我应该在哪里为我的 std::pair 特化定义运算符 >>?

标签 c++ stl template-specialization argument-dependent-lookup

考虑以下程序:

#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 namespace std unless otherwise specified. A program may add a template specialization for any standard library template to namespace std 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/

相关文章:

c++ - 在 C++ Map 中返回严格小于给定键的最大键

c++ - 显示所有匹配值的二进制搜索功能?

c++ - 为什么 Visual C++ 会在 delete[] 上覆盖这么多额外的内存?

c++ - 无法检测到 C++ 同步 boost::asio::ip::tcp::socket 连接被关闭

c++ - 获取对元组元素的引用

c++ - 从 map vector 中删除元素

c++ - 在 CMake 项目中包含 SOIL2 库

c++ - 特化一个模板类?

c++ - '仅将成员函数添加到类的专用模板

c++ - 如何使用模板模板参数专门化模板类的成员