C++17使用std::apply和fold expression对tuple进行遍历

版权声明:本文为博主原创文章,转载请注明原文出处! https://blog.csdn.net/T_27080901/article/details/82966314

C++17使用std::apply和fold expression对std::tuple进行遍历

std::apply函数

先来看这个std::apply函数,这个函数定义在tuple头文件中,函数签名如下:

template <class F, class Tuple>
constexpr decltype(auto) apply(F&& f, Tuple&& t);

该函数接受两个参数,第一个是一个函数对象,第二个是一个Tuple对象

来看一个最简单的示例:

#include <tuple>
#include <iostream>

int main() {
    // 两个元素相加
    std::cout << std::apply([](auto x, auto y) { return x + y; }, 
                            std::make_tuple(1, 2.0)) << '\n';
}

输出结果是3

这个例子中第一个参数使用Lambda匿名函数将tuple中的两个元素相加,第二个使用std::make_tuple函数构造一个只含有两个元素的tuple

fold expression

这个特性是C++ 17中我觉得很有用的一个新特性,使用规则有下面四条:

  1. Unary right fold ( E E o p op …) becomes ( E 1 E_1 o p op (… o p op ( E N 1 E_{N-1} o p op E N E_N )))

  2. Unary left fold (… o p op E E ) becomes ((( E 1 E_1 o p op E 2 E_2 ) o p op …) o p op E N E_N )

  3. Binary right fold ( E E o p op o p op I I ) becomes ( E 1 E_1 o p op (… o p op ( E N 1 E_{N−1} o p op ( E N E_N o p op I I ))))

  4. Binary left fold ( I I o p op o p op E E ) becomes (((( I I o p op E 1 E_1 ) o p op E 2 E_2 ) o p op …) o p op E N E_N )

这里的 E E 指的是Expression(符合C++语法的表达式), o p op 指的是operator(操作符), N N 是parameter pack(可变参数)的个数, I I 是一个常数。

可能看这个规则有些抽象,我们来看一些具体的例子:

#include <tuple>
#include <iostream>

int main() {
    // 多个元素相加,使用parameter pack
    std::cout << std::apply([](auto&& ... args) { return (args + ...); },
                            std::make_tuple(1, 2.f, 3.0)) << '\n';
    // 遍历tuple并输出,注意逗号操作符的使用
    std::apply([](auto&&... args) { ((std::cout << args << '\n'), ...); },
                std::make_tuple(1, 2.f, 3.0));
}

输出如下:

6
1
2
3

第6行中,std::apply函数的第一个参数是一个Lambda匿名函数,函数的参数是一个可变参数args,函数体中只有一条语句args + ...,这个情况就是上面的第一种情况:这里的 E E 就是args o p op 就是+,所以展开来就是 a r g s 1 + a r g s 2 + a r g s 3 args_1 + args_2 + args_3 (因为参数的个数是3)。

第9行中,Lambda匿名函数的函数体是((std::cout << args << '\n'), ...)这是一个逗号操作符,也属于上面四种情况中的第一种:这里的 E E 就是std::cout << args << '\n') o p op 就是,,所以这一行就打印输出了tuple的每一个元素。如果在C++17之前想要遍历tuple就比较麻烦,需要很多额外的操作。

参考资料

  1. std::apply
  2. fold expression

猜你喜欢

转载自blog.csdn.net/T_27080901/article/details/82966314