结构解引用运算符(运算符 - >)

时间:2011-12-16 19:13:10

标签: c++ templates iterator operator-overloading

我正在为迭代器编写一个瘦模板包装器,并在通过结构解除引用操作符时遇到绊脚石,主要是因为指针没有:

#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*’

以下方法有效,但我认为保证不起作用。也就是说,如果迭代器有一个奇怪的pointer类型,它与指向value_type的指针不同。

   pointer operator->() {return &*internal;} //MARK3

1 个答案:

答案 0 :(得分:10)

标准间接表示重载operator->必须返回指针,可转换为指针的对象或重载operator->的对象。您最好的选择是返回internal

§13.5.6 [over.ref] p1

  

表达式x->m被解释为(x.operator->())->m

(以上适用于递归。)