iterator Overload Member Selection vs Indirection Operator

北慕城南 提交于 2019-12-13 04:43:56

问题


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); }
};

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?


回答1:


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

Example usage:

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

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.




回答2:


The operator->() should return a pointer type of the type the container holds that the iterator is used on. So if you have a container that holds a std::string then the iterator::operator-> should return a std::sting*. In your case since you derive from std::iterator you can use the pointer typedef for the return type.



来源:https://stackoverflow.com/questions/37191290/iterator-overload-member-selection-vs-indirection-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!