迭代器重载成员选择与间接运算符

迭代器重载成员选择与间接运算符

本文介绍了迭代器重载成员选择与间接运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以为了创建一个我在这里创建了一个玩具迭代器(我知道它不完美,只是为了提问):

So in the interest of creating a Minimal. Complete, Verifiable Example I have created a toy iterator here (I know it's not perfect, it's just for the purposes of asking a question):

class foo : public iterator<input_iterator_tag, string> {
    string _foo;
    static const size_t _size = 13;
public:
    const string& operator*() { return _foo; }
    const foo& operator++() {
        _foo += '*';
        return *this;
    }
    const foo operator++(int) {
        auto result = *this;
        _foo += '*';
        return result;
    }
    bool operator==(const foo& rhs) { return _foo.empty() != rhs._foo.empty() && _foo.size() % _size == rhs._foo.size() % _size; }
    bool operator!=(const foo& rhs) { return !operator==(rhs); }
};

我读到需要定义成员选择运算符。间接运算符是有道理的,但会员选择运算符在这里让我感到困惑。如何为 foo 实施会员选择运营商?

I read that an InputIterator needs to have defined the Member Selection Operator. The Indirection Operator makes sense, but a Member Selection Operator is confusing to me here. How would an Member Selection Operator be implemented for foo?

推荐答案

const string* operator->() const { return &_foo; }

用法示例:

foo i;
++i;
assert(i->length() == 1);

这种方式的工作方式是编译器会重复调用运算符 - > 直到返回类型是一个原始指针(所以在这种情况下只需要一次调用 foo :: operator-> ),然后执行该指针上的常规成员选择操作。

The way this works is that the compiler will generate repeated calls to operator-> until the return type is a raw pointer (so in this case just one call to foo::operator->), then do the regular member selection operation on that pointer.

这篇关于迭代器重载成员选择与间接运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 00:48