【问题标题】:How to loop over a tuple at compile time?如何在编译时循环元组?
【发布时间】:2013-09-29 05:23:56
【问题描述】:

例如,我有一个元组

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

【问题讨论】:

  • How do I iterate over a tuple 的可能重复项
  • @JohnZwinck:这个问题有点宽泛,这导致了相当复杂的答案(与下面的 nurettin 相比)。

标签: c++ templates tuples


【解决方案1】:

你可以像这样使用 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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-18
    • 1970-01-01
    • 2013-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-03
    • 1970-01-01
    相关资源
    最近更新 更多