Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Structure dereference operator (operator->)

I am writing a thin template wrapper for iterators, and hit a stumbling block when passing through the structure dereference operator, mainly because pointers don't have one:

#include <vector>

struct mystruct {
    int member;
};

template<class iterator>
struct wrap {
   typedef typename std::iterator_traits<iterator>::pointer pointer;
   iterator internal;
   pointer operator->() {return internal.operator->();} //MARK1
};

int main() {
    wrap<std::vector<mystruct>::iterator> a;
    a->member;
    wrap<mystruct*> b;
    b->member;
    return 0;
}

http://ideone.com/XdvEz

prog.cpp: In member function ‘typename std::iterator_traits<_Iter>::pointer wrap<iterator>::operator->() [with iterator = mystruct*]’:
prog.cpp:18:   instantiated from here
prog.cpp:11: error: request for member ‘operator->’ in ‘((wrap<mystruct*>*)this)->wrap<mystruct*>::internal’, which is of non-class type ‘mystruct*’

This following method works, but I don't think it's guaranteed to work. Namely, if an iterator has a strange pointer type that isn't the same as a pointer to a value_type.

   pointer operator->() {return &*internal;} //MARK3
like image 355
Mooing Duck Avatar asked Dec 16 '11 19:12

Mooing Duck


1 Answers

The standard indirectly says that an overloaded operator-> has to either return a pointer, an object that is convertible to a pointer, or an object that has overloaded operator->. Your best bet is to just return internal.

§13.5.6 [over.ref] p1

An expression x->m is interpreted as (x.operator->())->m

(The above applies recursively.)

like image 96
Xeo Avatar answered Sep 19 '22 19:09

Xeo