BOOST_FOREACHに添え字を付けてみた

手段と目的が交差するとき、無駄努力が始まる。
ほしいという声を聞いたので、BOOST_FOEACHという素材を活かす方向でなんとか。


#include <iostream>
#include <vector>
#include <boost/foreach.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/assign/std/vector.hpp>

#define INDEX_FOREACH(elem, cont, n) \
INDEX_FOREACH_I(elem, cont, n, BOOST_PP_CAT(_index_foreach_label_, __LINE__))
#define INDEX_FOREACH_I(elem, cont, n, label) \
if (bool _index_foreach_break = false) {} else \
if (size_t _index_foreach_index = 0) {} else \
label: \
if (_index_foreach_break) {} else \
BOOST_FOREACH(elem, cont) \
for (bool _index_foreach_flag = true; \
_index_foreach_flag; \
_index_foreach_flag && (_index_foreach_break = true)) \
if (_index_foreach_break) { goto label; } else \
for (n = _index_foreach_index; \
_index_foreach_flag; \
++_index_foreach_index, _index_foreach_flag = false)

struct hoge {
int n;
hoge(int n) : n(n) {}
};

int main() {
int ar[] = {10,20,30,40,50,60};
INDEX_FOREACH (int n, ar, size_t i) {
if (i == 2) continue;
std::cout << i << ": " << n << '\n';
if (i == 4) break;
}

std::cout << "-------------------\n";

using boost::assign::operator+=;
std::vector<hoge> v;
v += 20,40,60,60,80,100;
INDEX_FOREACH (hoge const & x, v, size_t i) {
if (i % 2) continue;
std::cout << i << ": " << x.n << '\n';
break;
}
}

結果:http://ideone.com/BcH8i
書きながらこれでいいんじゃないかと思った