Fold Expressions in C++

Hi folks! In this tutorial, we are going to learn and implement Fold Expressions in C++. So let us understand first what are fold expressions.

Fold Expressions

This is a new feature in the C++ 17  compiler. It usually allows a user to apply the same set of binary operations to all the arguments. It works in the sequence of the first 2 arguments, then to the third, and so on…

For example:

 (...<bin_operation>args)

Compiler will predict this and and give

(args <bin_operation>args2)      

            <bin_operation>args3)          

               <bin_operation>args4) …… and so on.


C++ Source Code: Fold Expressions

Lets have a look at the example of a basic fold expression by taking sum as the list of arguments:

Read the comments in the code for better understanding.

#include <iostream>  //main header file
using namespace std; //for namespace std

template<typename ... T> //put templates
void sum(T ... vals)
{
    cout << "MERGED = " << (... + vals) << endl;; //output
}

int main()
{
    sum(9);  //=(9)
    sum(9, 10); //=(9+10)
    sum(9, 10, 11); //=((9+10)+11)
    sum(9, 10, 11, 12); //(((9+10)+11)+12)
    
    cout << endl;

    sum(1.1);
    sum(1.1, 1.2);
    sum(1.1, 1.2, 1.3);
    sum(1.1, 1.2, 1.3, 1.4);

    cout << endl;

    sum(std::string("A"));
    sum(std::string("Brown"), std::string("Dog"));
    sum(std::string("Jumps"), std::string("over"), 
                    std::string("a"));
    sum(std::string("A"), std::string("Brown"), 
                    std::string("Dog"), std::string("Jumps"));
    
    return 0;
}

Output:

MERGED = 9
MERGED = 19
MERGED = 30
MERGED = 42

MERGED = 1.1
MERGED = 2.3
MERGED = 3.6
MERGED = 5

MERGED = A
MERGED = BrownDog
MERGED = Jumpsovera
MERGED = ABrownDogJumps

Algorithm:

  1. Include header file.
  2. Template Typename argument is inserted.
  3. Add void sum value i.e. what we want to do in the templates in this case sum.
  4. Insert sum arguments in form of natural numbers in the first case.
  5. Insert sum arguments in form of decimal numbers in the second case.
  6. Insert sum arguments in form of words or alphabets in the third case.
  7. Output of the program will be obtained as sum of the fold expression in each case. Like 9=9 , ( 9,10 ) = 19 ,((9,10))+11), (((9+10)+11)+12)))

Note:

Fold expressions are available in C++ 17 compiler.

Fold expressions are always written in “()” brackets.

Leave a Reply

Your email address will not be published.