Boost logo

Boost Users :

Subject: [Boost-users] [foreach][auto] Mixing foreach and auto ?
From: Maxime van Noppen (maxime_at_[hidden])
Date: 2009-11-16 11:25:19


Hi list,

I'm a big fan of both foreach and auto facilities provided by Boost and
was thinking of merging the two. I searched in the list archives and saw
the question was discussed earlier but didn't find a clear reason on why
it shouldn't be done.

How bad is this quite simple solution :

> #define AUTO_FOREACH(VAR, COL) \
> BOOST_FOREACH_PREAMBLE() \
> if (boost::foreach_detail_::auto_any_t BOOST_FOREACH_ID(_foreach_col) = BOOST_FOREACH_CONTAIN(COL)) {} else \
> if (boost::foreach_detail_::auto_any_t BOOST_FOREACH_ID(_foreach_cur) = BOOST_FOREACH_BEGIN(COL)) {} else \
> if (boost::foreach_detail_::auto_any_t BOOST_FOREACH_ID(_foreach_end) = BOOST_FOREACH_END(COL)) {} else \
> for (bool BOOST_FOREACH_ID(_foreach_continue) = true; \
> BOOST_FOREACH_ID(_foreach_continue) && !BOOST_FOREACH_DONE(COL); \
> BOOST_FOREACH_ID(_foreach_continue) ? BOOST_FOREACH_NEXT(COL) : (void)0) \
> if (boost::foreach_detail_::set_false(BOOST_FOREACH_ID(_foreach_continue))) {} else \
> for (BOOST_AUTO(VAR, BOOST_FOREACH_DEREF(COL)); !BOOST_FOREACH_ID(_foreach_continue); BOOST_FOREACH_ID(_foreach_continue) = true)
>
> #define auto_foreach AUTO_FOREACH

It is basically the same code as BOOST_FOREACH (from boost 1.39) except
that last line where I added the BOOST_AUTO in the for initialization.

auto_foreach can then be used as :

> auto_foreach(i, container) // i is a copy
> auto_foreach(&i, container) // i is a reference
> auto_foreach(const &i, container) // is a const reference

This seems pretty cool and I don't see obvious pitfalls though I don't
know the exact magic behind both auto & foreach. Am I living dangerously
by using this auto_foreach ?

Thanks,

-- 
Maxime

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net