読者です 読者をやめる 読者になる 読者になる

BOOST_AUTO_FOREACH?

C++

BoostML - 【foreach】【auto】 Mixing foreach and auto ?


GCC 4.4ではコンパイル確認。

#include <iostream>
#include <vector>
#include <boost/typeof/typeof.hpp>
#include <boost/foreach.hpp>

#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

int main()
{
    std::vector<int> v;

    v.push_back(3);
    v.push_back(1);
    v.push_back(4);

    auto_foreach (i, v) {
        std::cout << i << std::endl;
    }
}
3
1
4

参照とconst参照もできます

auto_foreach (&i, v)
auto_foreach (const& i, v)