Fold Expressions

In this lesson, we'll study fold expressions.

We'll cover the following...

Fold Expressions (C++17)

Fold expressions is a nice syntax to evaluate binary operators at compile-time. Fold expressions reduce parameter packs on binary operators.

C++11 provides support for parameter packs:

Press + to interact
bool all_14(){
return true;
}
template<typename T, typename ...Ts>
bool all_14(T t, Ts ... ts){
return t && all_14(ts...);
}

C++17 provides support for fold expressions:

Press + to interact
template<typename ... Args>
bool all_17(Args ... args){
return ( ... && args);
}
bool val == all_14(true, true, true, false)
== all_17(true, true, true, false
== ((true && true)&& true)&& false
== false;

Two variations

  • The fold expression either has or does not have an initial value
  • The parameter pack will be processed from left or right

C++17 supports the following 32 operators in fold expressions:

+ - * / % ^ & | = < > << >> ...