c++ - How to allow range-for loop on my class? -
this question has answer here:
i have class this:
class foo { private: int a,b,c,d; char bar; double m,n public: //constructors here };
i wanna allow range-for loop on class, e.g.
foo foo {/*...*/}; for(auto& f : foo) { //f specific order such c,b,d,(int)m,(int)bar,a,(int)n }
how can achieve this? looking @ iterator don't know requirements range-for loop. (please don't ask me use array or stl type)
the loop defined equivalent to:
for ( auto __begin = <begin-expr>, __end = <end-expr>; __begin != __end; ++__begin ) { auto& f = *__begin; // loop body }
where <begin-expr>
foo.begin()
, or begin(foo)
if there isn't suitable member function, , likewise <end-expr>
. (this simplification of specification in c++11 6.5.4, particular case range lvalue of class type).
so need define iterator type supports pre-increment ++it
, dereference *it
, comparison i1 != i2
; , either
- give
foo
public member functionsbegin()
,end()
; or - define non-member functions
begin(foo)
,end(foo)
, in same namespacefoo
can found argument-dependent lookup.
Comments
Post a Comment