Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement operator-> for iterator type?

Is there a way to implement operator->, not only operator*. To have following code working:

Iterator<value> it = ...
i = (*it).get();
i = it->get(); // also works

Let we say that value type has method get. When Iterator is implemnted as below:

template<T> class Iterator {
    T operator*() { return ... }
    T operator->()  { return ... }
 }

Here ... is an implementation of getting right T object.

Somehow it won't work when I implement it in this way. I think I misunderstand something.

like image 519
kokosing Avatar asked Jan 25 '12 18:01

kokosing


2 Answers

operator-> should return a pointer:

T * operator->();
T const * operator->() const;

operator* should return a reference if you want to use it for modification:

T & operator*();
T operator*() const; // OR T const & operator*() const;
like image 176
Mike Seymour Avatar answered Oct 04 '22 10:10

Mike Seymour


As odd as this may seem, you want to return a pointer to T, thusly:

T * operator->() { return &the_value; }

Or a pointer to const.

like image 36
Benjamin Lindley Avatar answered Oct 04 '22 10:10

Benjamin Lindley