<<运算符使用迭代器作为参数 [英] Overloading of << operator using iterator as a parameter

查看:265
本文介绍了<<运算符使用迭代器作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢将枚举值作为文本打印并用于重载。假设我有以下代码:

I`d like to print enum values as text and use for it overloading. Suppose I have the following code:

#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <unordered_set>

enum enm{
    One,
    Two
};

class Complex{
public:
friend std::ostream& operator<<(std::ostream& out, std::unordered_multiset<int>::const_iterator i){
    switch (*i){
        case One:{
            return out<<"One";
        }
        case Two:{
            return out << "Two";
        }
    }
}
void func(std::unordered_multiset<int> _v);
};

void Complex:: func(std::unordered_multiset<int> _v){
    _v.insert(One);
    _v.insert(Two);
    for (std::unordered_multiset<int>::const_iterator i(_v.begin()), end(_v.end()); i != end; ++i){
        std::cout <<"Num: " << *i <<std::endl; //need to get here "One", "Two" instead of 0, 1
    }
}

int main(){
    Complex c;
    std::unordered_multiset<int> ms;
    c.func(ms);
    return 0;   
}

问题是这个变种doesn`t工作。所以,我得到0,1而不是一,二。没有想法如何正确地做。
谢谢您的帮助!

The problem is this variant doesn`t work. So, I get 0, 1 instead of One, Two. Have no ideas how to do it properly. Thank you for help!

推荐答案

我假设您将 i 更改为 * i ,以便于您的程序编译。为了打印迭代器,你必须做 i ,但这会失败,并出现编译错误。

I'm assuming you changed i to *i in order for your program to compile. In order to print the iterator you must do i, but this fails with a compiler error.

问题是插入运算符在它的第一个声明上被定义为类中的一个朋友,因此查找这个运算符只能依赖于与参数类型相关联的命名空间和类,一个称为 ADL 或Koenig查找。

The problem is that the insertion operator is defined as a friend within the class on its first declaration, so the lookup to find this operator can only depend on namespaces and classes associated with the argument types, a lookup referred to as ADL or Koenig lookup.

由于 std :: ostream unordered_multiset :: const_iterator 不与 Complex (请参阅 ADL#Details ),查找无法找到插入运算符。

Since std::ostream and unordered_multiset::const_iterator are not asscoiated with Complex (see ADL#Details), lookup fails to find the insertion operator.

在该类外部声明该函数,以便操作员正常无限制查找地点:

The solution is to declare the function outside of the class so that normal unqualified lookup for the operator takes place:

std::ostream& operator<<(std::ostream&, std::unordered_multiset<int>::const_iterator);
class Complex { .. };

但我建议您定义因为它似乎不需要访问 Complex (友好实体的目的的一部分)的私有/受保护成员。

I would recommend however that you define the operator outside of the class, as it doesn't seem to need to access private/protected members of Complex (part of the purpose of befriending entities).

这篇关于&lt;&lt;运算符使用迭代器作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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