名前空間
変種
操作

畳み込み式 (Fold expressions) (C++17以降)

From cppreference.com
< cpp‎ | language
 
 
C++言語
全般
フロー制御
条件実行文
if
繰り返し文 (ループ)
for
範囲for (C++11)
ジャンプ文
関数
関数宣言
ラムダ式
inline指定子
動的例外仕様 (C++17まで*)
noexcept指定子 (C++11)
例外
名前空間
指定子
const/volatile
decltype (C++11)
auto (C++11)
constexpr (C++11)
consteval (C++20)
constinit (C++20)
記憶域期間指定子
初期化
代替表現
リテラル
ブーリアン - 整数 - 浮動小数点数
文字 - 文字列 - nullptr (C++11)
ユーザー定義 (C++11)
ユーティリティ
属性 (C++11)
typedef宣言
型エイリアス宣言 (C++11)
キャスト
メモリ確保
クラス
クラス固有の関数プロパティ
explicit (C++11)
static

特殊メンバ関数
テンプレート
その他
 
 
 

パックを二項演算子で削減(畳み込み)する。

目次

[編集] 構文

( pack op ... ) (1)
( ... op pack ) (2)
( pack op ... op init ) (3)
( init op ... op pack ) (4)
1) 単項右畳み込み。
2) 単項左畳み込み。
3) 二項右畳み込み。
4) 二項左畳み込み。
op - 以下の32個の二項演算子のいずれか: + - * / % ^ & | = < > << >> += -= *= /= %= ^= &= |= <<= >>= == != <= >= && || , .* ->*。二項畳み込みでは、両方の op は同じでなければならない。
pack - 展開されていないパックを含み、トップレベルにキャストよりも低い優先順位の演算子を含まない式(正式には、cast-expression
init - 展開されていないパックを含まず、トップレベルにキャストよりも低い優先順位の演算子を含まない式(正式には、cast-expression

畳み込み式の開始括弧と終了括弧は必須であることに注意。

[編集] 解説

畳み込み式のインスタンス化は、式 e を次のように展開する。

1) 単項右畳み込み (E op ...)(E1 op (... op (EN-1 op EN))) となる。
2) 単項左畳み込み (... op E)(((E1 op E2) op ...) op EN) となる。
3) 二項右畳み込み (E op ... op I)(E1 op (... op (EN−1 op (EN op I)))) となる。
4) 二項左畳み込み (I op ... op E)((((I op E1) op E2) op ...) op EN) となる。

(ここで N はパック展開内の要素数)

例えば、

template<typename... Args>
bool all(Args... args) { return (... && args); }
 
bool b = all(true, true, true, false);
// within all(), the unary left fold expands as
//  return ((true && true) && true) && false;
// b is false

長さゼロのパック展開で単項畳み込みを使用する場合、以下の演算子のみが許可される。

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

[編集] 備考

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

template<typename... Args>
int sum(Args&&... args)
{
//  return (args + ... + 1 * 2);   // Error: operator with precedence below cast
    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>
 
// Basic usage, folding variadic arguments over operator<< 
template<typename... Args>
void printer(Args&&... args)
{
    (std::cout << ... << args) << '\n';
}
 
// Folding an expression that uses the pack directly over operator,
template<typename... Ts>
void print_limits()
{
    ((std::cout << +std::numeric_limits<Ts>::max() << ' '), ...) << '\n';
}
 
// Both a fold over operator&& using the pack
// and over operator, using the variadic arguments
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)), ...);
}
 
// Using an integer sequence to execute an expression
// N times by folding a lambda over operator,
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 Fold expressions [expr.prim.fold]
  • C++20 standard (ISO/IEC 14882:2020)
  • 7.5.6 Fold expressions [expr.prim.fold]
  • C++17 standard (ISO/IEC 14882:2017)
  • 8.1.6 Fold expressions [expr.prim.fold]

[編集] 欠陥報告

以下の動作変更を伴う欠陥報告が、以前に公開されたC++標準に遡って適用されました。

DR 適用対象 公開された動作 正しい動作
CWG 2611 C++17 畳み込み式の展開結果が括弧で囲まれていなかった 括弧で囲まれている
English 日本語 中文(简体) 中文(繁體)