3

たとえば、私はタプルを持っています

tuple<int, float, char> t(0, 1.1, 'c');

そしてテンプレート機能

template<class T> void foo(T e);

タプル要素を関数でループしたいのですが、boost::mpl::for_each を使用して以下を実装するなど、実装方法は?

template<class Tuple>
void loopFoo(Tuple t)
{
    foo<std::tuple_element<0, Tuple>::type>(std::get<0>(t));
    foo<std::tuple_element<1, Tuple>::type>(std::get<1>(t));
    foo<std::tuple_element<2, Tuple>::type>(std::get<2>(t));
    ...
}
4

1 に答える 1

5

次のように boost::fusion::for_each を使用できます。

#include <boost/fusion/algorithm/iteration/for_each.hpp>
#include <boost/fusion/adapted/std_tuple.hpp>

struct LoopFoo
{
  template <typename T> // overload op() to deal with the types
  void operator()(T const &t) const
  {
    /* do things to t */
  }
};

int main()
{
  auto t = std::make_tuple(0, 1.1, 'c');
  LoopFoo looper;
  boost::fusion::for_each(t, looper);
}
于 2013-09-29T06:38:18.247 に答える