🐭 Variadic Templates 与 Fold Expressions
现代 C++ 中可变参数模板 (Variadic Templates) 的引入,使得设计一个可以接收任意多个,任意类型参数的通用函数成为可能。标准库里面的 tuple 就是通过可变参数模板递归来实现的。折叠表达式 (Fold Expressions) 的引入进一步简化了实现的复杂度,用起来更加自然了。
折叠表达式展开规则:
| 表达式 | 类型 | 展开 |
|---|---|---|
| (… op e) | unary left fold | ((e1 op e2) op …) op eN |
| (e op …) | unary right fold | e1 op (… op (eN-1 op eN)) |
| **(init op … op e)** | binary left fold | (((init op e1) op e2) op …) op eN |
| (e op … op init) | binary right fold | e1 op (… op (eN-1 op (eN op init))) |
:::tips 注意这里总结的折叠表达式的展开过程,其实还是很好理解的,就是一个递归过程,一般使用右折叠的情况比较多,从左到右逐个处理传入的参数,比较符合人的认知习惯。 ::: 代码示例 :
#include <iostream>// fold expression, the ... dots// on the right-hand side of the operator, called a right fold// on the left- hand side of the operator, called a left fold// fold expression (op is ',')template <typename... Args> void print(Args... args) {((std::cout << args << ' '), ...);std::cout << "\n";}// fold expression (op is '=')template <typename... Args> void rprint(Args... args) {int dummy{};((std::cout << args << ' ', dummy) = ... = 0);std::cout << "\n";}// fold expression (op is '&&')template <typename T, typename... Ts> bool within(T min, T max, Ts... ts) {return ((min <= ts && ts <= max) && ...);}// fold expression (op is '+')template <typename R, typename... Ts> auto matches(const R &range, Ts... ts) {return (std::count(std::begin(range), std::end(range), ts) + ...);}int main() {print(1, 2.2, "3.3"); // 1 2.2 3.3rprint(1, 2.2, "3.3"); // 3.3 2.2 1std::cout << std::boolalpha << within(10, 20, 15, 30) << '\n'; // falsestd::cout << matches("abcdefg", 'a', 'd', 'f') << '\n'; // 3return 0;}
🐂 Lambda 与完美转发
我们知道模板函数结合完美转发可以设计非常通用的函数模板:
- T&& 类型推导
- std::forward
(t) 转发参数
其实 Lambda 也可以结合完美转发设计非常通用的 Lambda:
- auto && 类型推导
- std::forward
(t) 转发参数
代码示例 :
#include <iostream>class X {};void func(X &&x) { std::cout << "calls func(X &&x)\n"; }void func(X &x) { std::cout << "calls func(X &x)\n"; }void func(const X &x) { std::cout << "calls func(const X &x)\n"; }void func(volatile X &x) { std::cout << "calls func(volatile X &x)\n"; }auto fwd1 = [](auto &&... params) {// accept any type of arguments and forward them to funcreturn func(std::forward<decltype(params)>(params)...);};template <typename... Ts> auto fwd2(Ts &&... params) {// accept any type of arguments and forward them to funcreturn func(std::forward<Ts>(params)...);}int main() {// fwd can keeps the passed in value's cvr qualifierX x00{}, x01{};X x1{};const X x2{};volatile X x3{};fwd1(std::move(x00)); // calls func(X &&x)fwd1(x1); // calls func(X &x)fwd1(x2); // calls func(const X &x)fwd1(x3); // calls func(volatile X &x)fwd2(std::move(x01)); // calls func(X &&x)fwd2(x1); // calls func(X &x)fwd2(x2); // calls func(const X &x)fwd2(x3); // calls func(volatile X &x)return 0;}
:::tips 完美转发结合折叠表达式进而设计出通用函数模板与通用 Lambda 表达式 :::
🐯 总结
- 使用 std::forward 结合 decltype 转发 auto&& Lambda 参数
- 理解折叠表达式的展开规则,应用折叠表达式设计通用函数与通用 Lambda
