
I have a lot of handcoded loops that look something like this:
//////////////////////////////////////////////////////////////////////////////
#include <vector>
void f(float);
void g(std::vector<float> const & v) {
std::vector<float>::const_iterator const v_end = v.end();
for (std::vector<float>::const_iterator it = v.begin(); it != v_end; ++it)
f(*it);
}
//////////////////////////////////////////////////////////////////////////////
I need to replace it with something equivalent but simpler. I tried
BOOST_FOREACH (from boost-1.34):
//////////////////////////////////////////////////////////////////////////////
#include
From this I conclude that my macro is as good as a handcoded loop. (Although I of course wonder why the compiler chose to move "movl 4(%eax), %esi" further down and swap the parameters of cmpl from "%ebx, %esi" to "%esi, %ebx".)
But my macro is not as versatile as BOOST_FOREACH. Is there any way to improve it? In particular, is it possible get rid of the macro parameter value_type? Is it possible to make it work with other containers than vectors, as long as they define const_iterator/iterator, begin, end and value_type? Something like this maybe: ////////////////////////////////////////////////////////////////////////////// #define iterate_container_const(it, v) \ for \ (struct { \ typeof(v)::const_iterator current; \ typeof(v)::const_iterator const end; \ typeof(v)::value_type const & operator*() {return *current;} \ } it = {v.begin(), v.end()}; \ it.current != it.v_end; \ ++it.current) \ #include <vector> void f(float); void g(std::vector<float> const & v, std::list<float> const & l) { iterate_containter_const(it, v) f(*it); iterate_containter_const(it, l) f(*it); } ////////////////////////////////////////////////////////////////////////////// Or is it possible to configure BOOST_FOREACH to be as efficient as my macro?