폴드 표현식

폴드 표현식 (Fold expressions)

가변 인자 템플릿(variadic template)의 매개변수 팩(pack)을 이항 연산자로 축약해 주는 폴드 표현식을 알아볼게요. 팩 안의 요소들을 하나의 연산자로 차례로 묶어서 계산하고 싶을 때 쓰는 문법입니다.

출처: cppreference

본문

문법

    ( pack op ... ) (1)
    ( ... op pack ) (2)
    ( pack op ... op init ) (3)
    ( init op ... op pack ) (4)
  • (1) 단항 우측 폴드 (unary right fold)
  • (2) 단항 좌측 폴드 (unary left fold)
  • (3) 이항 우측 폴드 (binary right fold)
  • (4) 이항 좌측 폴드 (binary left fold)

| op | - | 다음 32개 이항 연산자 중 하나: + - * / % ^ & | = < > << >> += -= *= /= %= ^= &= |= <<= >>= == != <= >= && || , .* ->* 이항 폴드에서는 두 op가 같아야 해요. | | pack | - | 펼쳐지지 않은(unexpanded) 팩을 포함하고, 최상위 레벨에서 cast보다 우선순위가 낮은 연산자를 포함하지 않는 표현식 (정식으로는 cast-expression) | | init | - | 펼쳐지지 않은 팩을 포함하지 않고, 최상위 레벨에서 cast보다 우선순위가 낮은 연산자를 포함하지 않는 표현식 (정식으로는 cast-expression) |

여는 괄호와 닫는 괄호는 폴드 표현식에서 필수라는 점을 기억해 두세요.

설명

폴드 표현식의 인스턴스화는 표현식 e를 다음과 같이 확장해요:

  • 단항 우측 폴드 (E op ...)(E1 op ( ... op (EN-1 op EN)))
  • 단항 좌측 폴드 (... op E)(((E1 op E2) op ...) op EN)
  • 이항 우측 폴드 (E op ... op I)(E1 op (... op (EN−1 op (EN op I))))
  • 이항 좌측 폴드 (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

단항 폴드를 길이가 0인 팩 확장에 쓰는 경우에는 다음 연산자만 허용돼요:

  • 논리 AND (&&) — 빈 팩에 대한 값은 true
  • 논리 OR (||) — 빈 팩에 대한 값은 false
  • 콤마 연산자(,) — 빈 팩에 대한 값은 void()

참고 사항

init이나 pack으로 쓰는 표현식의 최상위 레벨에 cast보다 우선순위가 낮은 연산자가 있으면 반드시 괄호로 감싸야 해요:

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) | 폴드 표현식 | | | 202406L | (C++26) | 폴드 표현식을 포함하는 제약 조건의 순서 정하기 |

예제

여러 인자를 한 번에 처리하는 함수부터, 팩을 직접 사용하는 표현식, lamdba의 폴드까지 폴드 표현식의 다양한 쓰임을 확인해 볼게요.

#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

더 알아보기 (Learn more)