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

( fold 演算により) パック を二項演算子で畳み込みます。

目次

翻訳の説明: - 「Contents」を「目次」に翻訳しました - HTMLタグ、属性、クラス名はすべて保持されています - ` `内のテキストはC++関連の専門用語(Syntax, Explanation, Notes, Example, References, Defect reports)であるため、翻訳せずに保持しています - 番号部分はそのまま保持されています - 元のフォーマットと構造は完全に保持されています

構文

( pack op ... ) (1)
( ... op pack ) (2)
( pack op ... op init ) (3)
( init op ... op pack ) (4)
**注記**: この表はC++のfold式の構文を示しており、HTMLタグ内のコード部分は翻訳対象外のため、日本語訳は追加されていません。表の構造と数値ラベルは完全に保持されています。
1) 単項右畳み込み。
2) 単項左畳み込み。
3) バイナリ右畳み込み。
4) バイナリ左畳み込み。
op - 以下の32の 二項 演算子のいずれか: + - * / % ^ & | = < > << >> + = - = * = / = % = ^ = & = | = <<= >>= == ! = <= >= && || , . * - > * 。二項foldでは、両方の op は同じでなければならない。
pack - 未展開の pack を含み、トップレベルでcastよりも低い 優先順位 を持つ演算子を含まない式(形式的には cast-expression
init - 未展開の pack を含まず、トップレベルでcastよりも低い 優先順位 を持つ演算子を含まない式(形式的には cast-expression

開き括弧と閉じ括弧はフォールド式の必須要素であることに注意してください。

説明

fold 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となる

単項フォールドが長さゼロのパック展開で使用される場合、以下の演算子のみが許可されます:

1) 論理AND ( && )。空パックの値は true です。
2) 論理OR ( || )。空パックの値は false です。
3) コンマ演算子 ( , )。空パックの値は void ( ) です。

注記

init または pack として使用される式のトップレベルでキャストよりも 優先順位 が低い演算子を含む場合、その式は括弧で囲む必要があります:

template<typename... Args>
int sum(Args&&... args)
{
//  return (args + ... + 1 * 2);   // エラー: キャストより優先順位が低い演算子
    return (args + ... + (1 * 2)); // OK
}
機能テストマクロ 標準 機能
__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)), ...);
}
// 整数シーケンスを使用してラムダ式を 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++規格に対して遡及的に適用されました。

DR 適用対象 公開時の動作 正しい動作
CWG 2611 C++17 fold式の展開結果が括弧で囲まれていなかった 括弧で囲まれる