Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between BOOST_FOREACH and c++11 for range based loop?

  1. What are the main differences between BOOST_FOREACH and c++11 range based loop?
  2. Is there a specific situation where I would want to use BOOST_FOREACH instead of range based loop or vice versa?

After executing a little test with std::vector filled with 1,000,000 int variables I found out that BOOST_FOREACH is a little bit slower than range based loop (took about 1.25 times longer than for a ranged based loop).

like image 256
Laurynas Lazauskas Avatar asked Nov 19 '14 21:11

Laurynas Lazauskas


1 Answers

The main difference is that range-for is a language construct, while BOOST_FOREACH is a macro doing lots of magic under the hood to do something that looks like that language construct. It is trying to do exactly the same thing with the limitations of pre-C++11. The goal of BOOST_FOREACH is range-for.

There is exactly one situation where I would even think of using BOOST_FOREACH instead of range-for, and it is iterating over a container of tuples where you want to unroll the tuple:

std::map<int, int> m;
int key, value;
BOOST_FOREACH(boost::tie(key, value), m)
{
    // do something with key and value here
}

as compared to:

int key, value;
for (const auto& pair : m) 
{
    std::tie(key, value) = pair;
    // do something
}

I like that you can put the tie directly into the loop header, although ultimately that's such a minor advantage that it's hardly worth even considering this as being a decision. Use range-for. Always.


C++17 will introduce structured bindings, which remove even that minor syntactical advantage:

for (auto const& [key, value] : m)
{
    // do something
}

At that point, there will be no reason whatsoever to use BOOST_FOREACH.

like image 104
Barry Avatar answered Oct 24 '22 18:10

Barry