【问题标题】:iterating over tuple's elements in a specified sequential order以指定的顺序迭代元组的元素
【发布时间】:2016-01-22 20:30:50
【问题描述】:

可以遍历元组的元素并通过这种实现应用函数:

#include <tuple>
#include <utility>

template<class... Args>
void swallow(Args&&...)
{
}

template<size_t... Indices, class Function, class Tuple>
void tuple_for_each_in_unspecified_order_impl(std::index_sequence<Indices...>, Function f, const Tuple& t)
{
  swallow(f(std::get<Indices>(t))...);
}

template<class Function, class... Types>
void tuple_for_each_in_unspecified_order(Function f, const std::tuple<Types...>& t)
{
  tuple_for_each_in_unspecified_order_impl(std::index_sequence_for<Types...>(), f, t);
}

由于此实现依赖于传递给swallow() 函数的参数顺序,因此未指定f 的调用顺序。

强制f 的调用与元组元素的顺序一致的一种方法是使用递归:

template<class Function, class Tuple>
void tuple_for_each_in_order_impl(std::index_sequence<>, Function f, const Tuple& t) {}

template<size_t I, size_t... Indices, class Function, class Tuple>
void tuple_for_each_in_order_impl(std::index_sequence<I,Indices...>, Function f, const Tuple& t)
{
  f(std::get<I>(t));

  tuple_for_each_in_order_impl(std::index_sequence<Indices...>(), f, t);
}

template<class Function, class... Types>
void tuple_for_each_in_order(Function f, const std::tuple<Types...>& t)
{
  tuple_for_each_in_order_impl(std::index_sequence_for<Types...>, f, t);
}

这种递归解决方案的问题在于它可能会带来令人失望的编译时性能。

是否有更有效的解决方案可以产生所需的评估顺序?

我知道有许多用于元编程和元组操作的优秀 c++ 库可用,但我对解决方案的实现细节感兴趣,如果存在的话。

【问题讨论】:

标签: c++ tuples metaprogramming operator-precedence


【解决方案1】:

在 C++1z 中,将其折叠在逗号运算符上:

(... , void(f(get<Indices>(t))));

在此之前,解压成一个braced-init-list,例如:

auto l = {0, (void(f(get<Indices>(t))), 0)... };
(void) l;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-21
    • 2015-12-09
    • 2018-08-02
    • 1970-01-01
    • 2014-04-22
    • 2011-07-25
    • 2015-06-02
    相关资源
    最近更新 更多