3

For example, I have a tuple

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

and a template function

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

and I want to loop the tuple element with the function, how to implement it, like using boost::mpl::for_each to implement the following?

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));
    ...
}
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
user1899020
  • 13,167
  • 21
  • 79
  • 154
  • possible duplicate of [How do I iterate over a tuple](http://stackoverflow.com/questions/4532543/how-do-i-iterate-over-a-tuple) – John Zwinck Sep 29 '13 at 06:34
  • @JohnZwinck: the question was a bit broader and this led to quite complicated answers (compare to nurettin's one below). – Matthieu M. Sep 29 '13 at 11:35

1 Answers1

5

You can use boost::fusion::for_each like this:

#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);
}
nurettin
  • 11,090
  • 5
  • 65
  • 85