如何在编译时循环一个元组?

时间:2013-09-29 05:23:56

标签: c++ templates tuples

例如,我有一个元组

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));
    ...
}

1 个答案:

答案 0 :(得分: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);
}