C++ 17 – Fold Expressions

Parameter Pack in C++ is denoted as “…”. When this is used in function as an argument along with template class, it can take a variable number of arguments of the same or different data types.

template <typename... Args>
auto product(Args... args) {
    // body

With C++ 17, we can perform a binary operator on a parameter pack with a sequence of values using fold expressionFold expression keeps it simple, and we do not have to write elaborate code to traverse the list to do the operation. It looks as below for the previous function.

auto ret = args * ...;

The above statement would calculate the product on all the values stored in args. The statement is called the Fold Expression.

Let us see a complete program using fold expression and the above product calculation in action. The program is available for download at https://github.com/codeversionmaster/cplusplus/blob/cplusplus17/fold_expr.cpp.

$ cat fold_expr.cpp 
#include <iostream>

template <typename... Args>
auto calculate_product(Args... args) {

    //Fold Expression that does "*" on all the values inside "args"
    auto ret = (args * ...);
    return ret;

int main() {
    int product;
    product = calculate_product(2, 3, 4, 5);
    std::cout << "Product is " << product << std::endl;

    product = calculate_product(2, 3, 4, 5, 6);
    std::cout << "Product is " << product << std::endl;
    return 0;

You can compile and run the program and see that a variable number of arguments are passed each time. The product is calculated with just one line of Fold Expression.

$ g++ -std=c++17 fold_expr.cpp -o fold_expr
$ ./fold_expr 
Product is 120
Product is 720