Like many people these days I have been trying the different features that C++11 brings. One of my favorites is the \"range-based for loops\".
I understand that:
Should I just specialize begin() and end() ?
As far as I know, that is enough. You also have to make sure that incrementing the pointer would get from the begin to the end.
Next example (it is missing const version of begin and end) compiles and works fine.
#include
#include
int i=0;
struct A
{
A()
{
std::generate(&v[0], &v[10], [&i](){ return ++i;} );
}
int * begin()
{
return &v[0];
}
int * end()
{
return &v[10];
}
int v[10];
};
int main()
{
A a;
for( auto it : a )
{
std::cout << it << std::endl;
}
}
Here is another example with begin/end as functions. They have to be in the same namespace as the class, because of ADL :
#include
#include
namespace foo{
int i=0;
struct A
{
A()
{
std::generate(&v[0], &v[10], [&i](){ return ++i;} );
}
int v[10];
};
int *begin( A &v )
{
return &v.v[0];
}
int *end( A &v )
{
return &v.v[10];
}
} // namespace foo
int main()
{
foo::A a;
for( auto it : a )
{
std::cout << it << std::endl;
}
}