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
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With