← 模式

将元组应用于函数

12345678910111213141516171819202122232425262728293031#include <cstddef> #include <tuple> #include <type_traits> #include <utility> template<typename F, typename Tuple, size_t ...S > decltype(auto) apply_tuple_impl(F&& fn, Tuple&& t, std::index_sequence<S...>) { return std::forward<F>(fn)(std::get<S>(std::forward<Tuple>(t))...); } template<typename F, typename Tuple> decltype(auto) apply_from_tuple(F&& fn, Tuple&& t) { std::size_t constexpr tSize = std::tuple_size<typename std::remove_reference<Tuple>::type>::value; return apply_tuple_impl(std::forward<F>(fn), std::forward<Tuple>(t), std::make_index_sequence<tSize>()); } int do_sum(int a, int b) { return a + b; } int main() { int sum = apply_from_tuple(do_sum, std::make_tuple(10, 20)); }

此模式采用 CC0 公共领域贡献 许可。

需要 c++14 或更新版本。

意图

将一个元组解包作为函数的参数。

描述

第 12-21 行apply_from_tuple 函数模板返回将函数 fn 应用于存储在 std::tuple t 中的值所得到的结果。在第 15-16 行,我们将 t 的大小存储在 tSize 中,它被声明为 constexpr,以便在编译时求值。在第 18-20 行,我们调用 apply_tuple_impl,并传入 tfn 以及一个 std::index_sequence,该序列携带一个包含从 0tSize - 1 的整数序列的参数包。

第 6-10 行apply_tuple_impl 函数模板返回将函数 fn 应用于元组 t 的每个元素作为参数所得到的结果(在第 9 行)。为此,我们展开由 std::index_sequence 携带的参数包,并对序列中的每个整数,将 std::get 应用于元组。通过这种方式,t 的所有元素都被展开并传递给函数。

注意std::apply 函数已被提议作为 Library Fundamentals TS 的一部分,以便未来进行标准化。

贡献者

  • Joseph Mansfield
  • Marco Arena

最后更新

2017年12月9日

来源

在 GitHub 上 Fork 此模式

分享