kokosing
kokosing

Reputation: 5601

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.

Upvotes: 20

Views: 15928

Answers (3)

Fiktik
Fiktik

Reputation: 1941

You don't specify what "it won't work" means - does it fail to compile, or does something else than expected? I will assume it compiles, because from your snippet I can't see why it shouldn't.

What you are doing is returning by value. So you return a new instance of the pointed-to object. You instead should return a pointer in operator-> and reference in operator*

Upvotes: 2

Mike Seymour
Mike Seymour

Reputation: 254751

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;

Upvotes: 24

Benjamin Lindley
Benjamin Lindley

Reputation: 103751

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.

Upvotes: 7

Related Questions