boost::tuple で for_each のような処理

for_each のように各値に対して捜査するような処理が欲しかったので書いてみた。

#include <assert.h>
#include <boost/tuple/tuple.hpp>

namespace detail{

template<int N>
struct int2type{
    static const int value = N;
};

using boost::tuples::length;

template<typename tuple_t, typename F, int index>
void
tuple_for_each_impl(tuple_t& tuple, F& func, int2type<index>){
    func(tuple.get<index>());
    tuple_for_each_impl(tuple, func, int2type<index+1>());
}

template<typename tuple_t, typename F>
void
tuple_for_each_impl(tuple_t&, F&, int2type<length<tuple_t>::value>){}

}    // namespace detail


template<typename tuple_t, typename F>
void
tuple_for_each(tuple_t& tuple, F func){
    detail::tuple_for_each_impl(tuple, func, detail::int2type<0>());
}

int
main(){
    
    int sum = 0;
    tuple_for_each(boost::make_tuple(1, 4, 8), [&sum](int src){sum += src;});
    assert(sum == (1 + 4 + 8) );
    
    return 0;
}

ただし、型がバラバラの場合は、テンプレート関数で受け取る必要があるので
関数オブジェクトにする必要がある。

struct disp_{
    template<typename T>
    void operator ()(T& src){
        std::cout << src << " ";
    }
} disp;

int
main(){
    
    tuple_for_each(boost::make_tuple(1, 3.14f, 'w'), disp);
    
    return 0;
}
1 3.14f w

※ソースが古かったので修正

[boost]
ver 1.44.0

[参照]
http://lists.boost.org/Archives/boost/2004/09/72919.php