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

查看:13
本文介绍了我应该在哪里定义操作符 >>对于我对 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 在命名空间 std 中找到运算符 >>,它就不再考虑全局范围,无论在 std 中找到的运算符是否是可行的候选者.这比较不方便.如果我将我的运算符 >> 的声明放入命名空间 std(这在技术上是非法的)中,代码将按预期编译.除了将 point 设为我自己的类,而不是将其定义为 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?

提前致谢

推荐答案

namespace std 中添加 operator>> 的重载是被禁止的,但是添加了模板特化有时是允许的.

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

然而,这里没有用户定义的类型,标准类型上的操作符不是你重新定义的.专门化 operator>>(istream&, pair) 是合理的.

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.

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

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

如果 C++ 程序向命名空间 std 或命名空间 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天全站免登陆