我应该在哪里定义运算符>>为我的std :: pair的专业化? [英] Where should I define operator >> for my specialization of std::pair?

查看:167
本文介绍了我应该在哪里定义运算符>>为我的std :: pair的专业化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下程序:

#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在namespace std中找到operator >>,它就不再考虑全局范围,而不管在std中找到的运算符是否可行候选者。这是相当不方便。如果我把我的操作符>>的声明放到namespace std(这在技术上是非法的),代码编译良好,如预期。有没有办法解决这个问题,除了点我自己的类,而不是typedefing它作为std命名空间中的模板的特殊化?

This fails to compile because as soon as ADL finds operator >> in namespace std it doesn't consider the global scope any more regardless of whether the operator found in std was a viable candidate or not. This is rather inconvenient. If I place the declaration of my operator >> into namespace std (which is technically illegal) the code compiles well as expected. Is there any way to resolve this issue other than make point my own class rather than typedefing it as a specialization of a template in std namespace?

提前感谢

推荐答案

添加 operator> / code>在命名空间std 是禁止的,但有时允许添加模板专业化。

Adding an overload of operator>> in namespace std is forbidden, but adding a template specialization is sometimes allowed.

,这里没有用户定义的类型,标准类型的操作符不是要重新定义的。 operator>>(istream& pair< mytype,int>)的专业化是合理的。

However, there are no user-defined types here, and the operators on standard types are not yours to redefine. Specializing operator>>(istream&, pair<mytype, int>) would be reasonable.

[namespace.std] (n3290的第17.6.4.2.1节)说

section [namespace.std] (section 17.6.4.2.1 of n3290) says


如果向命名空间 std 添加声明或定义或在命名空间<$ c中添加命名空间,C ++程序的行为是未定义的$ c> std ,除非另有说明。 程序可以为任何标准库模板添加模板专用化,只有当声明依赖于用户定义的类型且命名空间 std

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.

(强调我)

这篇关于我应该在哪里定义运算符&gt;&gt;为我的std :: pair的专业化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆