Folding expressions in C++ 17

Setup your dev tools to use C++ 17

Using CLion (or CMake) and setting the CMakeLists.txt CMAKE_CXX_STANDARD to

set(CMAKE_CXX_STANDARD 17)

allows us to use C++ 17 features.

In CLion the intellisense/editor will show folding expressions with red underlines, i.e. as errors in the current release, however the code will compile

Folding Expressions

Basically folding expressions allow us to write code which takes one or more arguments and applies operators to them to create a return value.

In C++ terms, folding expressions take variadic template arguments and unpack the arguments using unary or binary operators to create a return value.

The syntax for folding expressions, is as follows

Syntax (as taken from http://en.cppreference.com/w/cpp/language/fold).

  • unary right fold (pack op …)
  • unary left fold (… op pack)
  • binary right fold (pack op … op init)
  • binary left fold (init op … op pack)

Let’s look at some examples to make things clearer using this syntax.

Unary right fold

The following is a simple summation method using unary right fold syntax

template<typename... Args>
auto unary_right_fold(Args... args) {
    return (args + ...);
}

Unary left fold

The following is a simple summation method using unary left fold syntax

template<typename... Args>
auto unary_left_fold(Args... args) {
    return (... + args);
}

Binary right fold

The following is a simple summation + 1 method using binary left fold syntax

template<typename... Args>
auto binary_right_fold(Args... args) {
    return (args + ... + 1);
}

Binary left fold

The following is a simple 1 + summation method using binary left fold syntax

template<typename... Args>
auto binary_left_fold(Args... args) {
    return (1 + ... + args);
}