C++中的折叠表达式

取自 A Tour of C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <concepts>
#include <ostream>

template<typename T>
concept Printable = requires (T t, std::ostream& os) {
{ os << t } -> std::same_as<std::ostream&>;
};

template<Printable... T>
void print(T&&... args) {
(std::cout << ... << args) << '\n';
}

int main() {
print("Hello ", 2026);
}

C++17 引入了折叠表达式,用于将一个包用二元运算符进行规约操作,有四种形式:

  • 一元右折叠:(E op ...) => $(E_1 \text{ op } (\dots \text{ op } (E_{N-1} \text{ op } E_N)))$
  • 一元左折叠:(... op E) => $(((E_1 \text{ op } E_2) \text{ op } \dots) \text{ op } E_N)$
  • 二元右折叠:(E op ... op I) => $(E_1 \text{ op } (\dots \text{ op } (E_{N-1} \text{ op } (E_N \text{ op } I))))$
  • 二元左折叠:(I op ... op E) => $((((I \text{ op } E_1) \text{ op } E_2) \text{ op } \dots) \text{ op } E_N)$

进一步了解可参看cppreference