c++ - 按指定的顺序迭代元组的元素

标签 c++ tuples metaprogramming operator-precedence

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

#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++1z 中,将其折叠到逗号运算符上:

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

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

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

关于c++ - 按指定的顺序迭代元组的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34955436/

相关文章:

c++ - 新 std::map 条目中指针的默认值

c++ - QT中如何检查是否按下了[Shift + Tab]

c++ - 使用元组累加器减少推力

python - 分配给看起来像元组的东西时创建的变量的生命周期

macros - 为什么 Elixir Logger 由宏组成?

Python:动态地向对象添加字段

具有重载访问器函数的单例上的 C++ 未解析外部

python - 如何使用 python 在 2D 列表中找到特定行的子集数量?可以使用收藏品的计数器功能吗?

python - 使用 python 驱动程序在 Cassandra 中插入一个元组字段

metaprogramming - 消除Julia元编程中的各种引用机制