可以迭代元组的元素并通过这种实现应用函数:
#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/