Did you ever went through the process of replacing the BOOST_FOREACH
by the range-based for
loop? Are there any gotchas when doing it mechanically (i.e. not doing a deep study of the code around).
Background: I do have sources with about 250K lines, compiled with Microsoft VC++ 10 (Visual Studio 2010). The code uses also BOOST_FOREACH from the boost library. I am just trying the VC++ 11 (Visual Studio 2012 RC) that implements also the range-based for
loop with the auto
.
So far, I have met the situation where the element was declared outside the BOOST_FOREACH
(no declaration in the parentheses):
BOOST_FOREACH (element, container) {
...
}
... and the element
was expected to have the value set in the loop after the break
. Can you remember similar problems?
When the BOOST_FOREACH
contains the declaration, would you choose to replace the explicit type by auto
? Is there any advantage to do so when one just mechanically rewrites the BOOST_FOREACH
instead of leaving the explicit declaration there?
Thanks for your help, Petr
The advantage of auto
over using the actual type or reference type is that the code will continue to work if the container type changes. This may not be what you want if you're intentionally performing a type conversion on the result of indirecting the container iterator.
Example:
std::vector<int> v;
for (int i: v) ...
If v
changes to std::vector<long>
or std::vector<unsigned>
then the type conversion may be unwanted; still, a compiler warning should catch this (especially for a narrowing conversion). On the other hand, you could have code where a (widening) conversion is intended:
std::vector<char> v;
for (int i: v) ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With