Namespaces
Variants

Fold expressions (since C++17)

From cppreference.net
C++ language
General topics
Flow control
Conditional execution statements
Iteration statements (loops)
Jump statements
Functions
Function declaration
Lambda function expression
inline specifier
Dynamic exception specifications ( until C++17* )
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
constexpr (C++11)
consteval (C++20)
constinit (C++20)
Storage duration specifiers
Initialization
Expressions
Alternative representations
Literals
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
typedef declaration
Type alias declaration (C++11)
Casts
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
Miscellaneous

通过二元运算符进行 折叠 归约。

目录

语法

( 包 操作符 ... ) (1)
( ... 操作符 包 ) (2)
( 包 操作符 ... 操作符 初始值 ) (3)
( 初始值 操作符 ... 操作符 包 ) (4)
1) 一元右折叠。
2) 一元左折叠。
3) 二元右折叠。
4) 二元左折叠。
op - 以下32种 二元 运算符中的任意一种: + - * / % ^ & | = < > << >> + = - = * = / = % = ^ = & = | = <<= >>= == ! = <= >= && || , . * - > * 。在二元折叠中,两个 op 必须相同。
pack - 包含未展开 pack 且顶层不包含优先级低于强制类型转换的运算符的表达式(形式上是 cast-expression
init - 不包含未展开 pack 且顶层不包含优先级低于强制类型转换的运算符的表达式(形式上是 cast-expression

请注意,开头和结尾的圆括号是折叠表达式必需的部分。

说明

一个 折叠表达式 的实例化会按以下方式展开表达式 e

1) 一元右折叠 (E op ...) 展开为 (E 1 op ( ... op (E N-1 op E N )))
2) 一元左折叠 (... op E) 展开为 (((E 1 op E 2 ) op ... ) op E N )
3) 二元右折叠 (E op ... op I) 展开为 (E 1 op ( ... op (E N−1 op (E N op I))))
4) 二元左折叠 (I op ... op E) 展开为 ((((I op E 1 ) op E 2 ) op ... ) op E N )

(其中 N 是包展开中的元素数量)

例如,

template<typename... Args>
bool all(Args... args) { return (... && args); }
bool b = all(true, true, true, false);
// 在 all() 函数内部,一元左折叠展开为
//  return ((true && true) && true) && false;
// b 的值为 false

当一元折叠表达式用于长度为0的包展开时,仅允许以下运算符:

1) 逻辑与 ( && )。空包的值是 true
2) 逻辑或( || )。空包的值是 false
3) 逗号运算符( , )。空包的值是 void ( )

注释

如果用作 init pack 的表达式在顶层包含优先级低于类型转换的运算符,则必须使用括号括起来:

template<typename... Args>
int sum(Args&&... args)
{
//  return (args + ... + 1 * 2);   // 错误:运算符优先级低于类型转换
    return (args + ... + (1 * 2)); // 正确
}
特性测试宏 标准 特性
__cpp_fold_expressions 201603L (C++17) 折叠表达式

示例

#include <climits>
#include <concepts>
#include <cstdint>
#include <iostream>
#include <limits>
#include <type_traits>
#include <utility>
#include <vector>
// 基础用法:在 operator<< 上折叠可变参数
template<typename... Args>
void printer(Args&&... args)
{
    (std::cout << ... << args) << '\n';
}
// 在直接使用参数包的表达式上通过 operator, 进行折叠
template<typename... Ts>
void print_limits()
{
    ((std::cout << +std::numeric_limits<Ts>::max() << ' '), ...) << '\n';
}
// 同时使用 operator&& 对参数包进行折叠
// 以及使用 operator, 对可变参数进行折叠
template<typename T, typename... Args>
void push_back_vec(std::vector<T>& v, Args&&... args)
{
    static_assert((std::is_constructible_v<T, Args&&> && ...));
    (v.push_back(std::forward<Args>(args)), ...);
}
// 使用整数序列通过 lambda 表达式在 operator, 上进行折叠
// 来执行表达式 N 次
template<class T, std::size_t... dummy_pack>
constexpr T bswap_impl(T i, std::index_sequence<dummy_pack...>)
{
    T low_byte_mask = static_cast<unsigned char>(-1);
    T ret{};
    ([&]
    {
        (void)dummy_pack;
        ret <<= CHAR_BIT;
        ret |= i & low_byte_mask;
        i >>= CHAR_BIT;
    }(), ...);
    return ret;
}
constexpr auto bswap(std::unsigned_integral auto i)
{
    return bswap_impl(i, std::make_index_sequence<sizeof(i)>{});
}
int main()
{
    printer(1, 2, 3, "abc");
    print_limits<uint8_t, uint16_t, uint32_t>();
    std::vector<int> v;
    push_back_vec(v, 6, 2, 45, 12);
    push_back_vec(v, 1, 2, 9);
    for (int i : v)
        std::cout << i << ' ';
    std::cout << '\n';
    static_assert(bswap<std::uint16_t>(0x1234u) == 0x3412u);
    static_assert(bswap<std::uint64_t>(0x0123456789abcdefull) == 0xefcdab8967452301ULL);
}

输出:

123abc
255 65535 4294967295 
6 2 45 12 1 2 9

参考文献

  • C++23 标准 (ISO/IEC 14882:2024):
  • 7.5.6 折叠表达式 [expr.prim.fold]
  • C++20 标准 (ISO/IEC 14882:2020):
  • 7.5.6 折叠表达式 [expr.prim.fold]
  • C++17 标准 (ISO/IEC 14882:2017):
  • 8.1.6 折叠表达式 [expr.prim.fold]

缺陷报告

以下行为变更缺陷报告被追溯应用于先前发布的C++标准。

缺陷报告 应用于 发布时的行为 正确行为
CWG 2611 C++17 折叠表达式的展开结果未用括号括起 用括号括起