I have a class like this:
class Foo {
private:
int a,b,c,d;
char bar;
double m,n
public:
//constructors here
};
I wanna allow range-for loop on my class, e.g.
Foo foo {/*...*/};
for(auto& f : foo) {
//f will be a specific order such as c,b,d,(int)m,(int)bar,a,(int)n
}
How can I achieve this? I was looking at iterator but don't know what are the requirements for a range-for loop. (Please don't ask me to use array or STL type)
Here is a basic framework I came up with:
If you have a basic understanding of variadic templates, I think the code is self-explanatory.
Usage is simple:
A POC can be found on ideone
This seems fairly un-C++-like, and rather prone to breakage. What if the iteration order is changed (accidentally or not) during some update in the future? Clients relying on a specific order will break.
All that said if you wish to support this all you have to do is implement your own iterator and provide
begin
/end
methods (or free functions with those names) to provide access. Then the iterator takes care of remembering which attribute it's currently looking at and provides it when dereferenced.The loop is defined to be equivalent to:
where
<begin-expr>
isfoo.begin()
, orbegin(foo)
if there isn't a suitable member function, and likewise for<end-expr>
. (This is a simplification of the specification in C++11 6.5.4, for this particular case where the range is a lvalue of class type).So you need to define an iterator type that supports pre-increment
++it
, dereference*it
and comparisoni1 != i2
; and eitherfoo
public member functionsbegin()
andend()
; orbegin(foo)
andend(foo)
, in the same namespace asfoo
so that they can be found by argument-dependent lookup.