CppDS.com

C++ 98 11 14 17 20 手册

折叠表达式(C++17 起)

来自cppreference.com
< cpp‎ | language

以二元运算符对形参包进行规约(折叠)。

语法

( 形参包 op ... ) (1)
( ... op 形参包 ) (2)
( 形参包 op ... op 初值 ) (3)
( 初值 op ... op 形参包 ) (4)
1) 一元右折叠
2) 一元左折叠
3) 二元右折叠
4) 二元左折叠
op - 任何下列 32 个二元运算符之一:+ - * / % ^ & | = < > << >> += -= *= /= %= ^= &= |= <<= >>= == != <= >= && || , .* ->*。在二元折叠中,两个 op 必须相同。
形参包 - 含未展开的形参包且其顶层不含有优先级低于转型(正式而言,是 转型表达式)的运算符的表达式
初值 - 不含未展开的形参包且其顶层不含有优先级低于转型(正式而言,是 转型表达式)的运算符的表达式

注意开与闭括号是折叠表达式的一部分。

解释

折叠表达式的实例化按如下方式展开成表达式 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

将一元折叠用于零长包展开时,仅允许下列运算符:

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

注解

若用作 初值形参包 的表达式在顶层具有优先级低于转型的运算符,则它可以加括号:

template<typename ...Args>
int sum(Args&&... args) {
//    return (args + ... + 1 * 2); // 错误:优先级低于转型的运算符
    return (args + ... + (1 * 2)); // OK
}

示例

#include <iostream>
#include <vector>
#include <climits>
#include <cstdint>
#include <type_traits>
#include <utility>
 
template<class ...Args>
void printer(Args&&... args) {
    (std::cout << ... << args) << '\n';
}
 
template<class T, class... Args>
void push_back_vec(std::vector<T>& v, Args&&... args)
{
    static_assert((std::is_constructible_v<T, Args&> && ...));
    (v.push_back(args), ...);
}
 
// 基于 http://stackoverflow.com/a/36937049 的编译时端序交换 
template<class T, std::size_t... N>
constexpr T bswap_impl(T i, std::index_sequence<N...>) {
  return (((i >> N*CHAR_BIT & std::uint8_t(-1)) << (sizeof(T)-1-N)*CHAR_BIT) | ...);
}
template<class T, class U = std::make_unsigned_t<T>>
constexpr U bswap(T i) {
  return bswap_impl<U>(i, std::make_index_sequence<sizeof(T)>{});
}
 
int main()
{
    printer(1, 2, 3, "abc");
 
    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 << ' ';
 
    static_assert(bswap<std::uint16_t>(0x1234u)==0x3412u);
    static_assert(bswap<std::uint64_t>(0x0123456789abcdefULL)==0xefcdab8967452301ULL);
}

输出:

123abc
6 2 45 12 1 2 9
关闭