• Joseph

Fold Expression in C++17

Updated: Nov 9




A fold expression is an instruction for the compiler to repeat the application of an operator over a parameter pack. This is especially useful when you need to apply the same operator to a set of arguments, but you are unsure of the number. For instance, the sum of N numbers is a common operation used in many scenarios. But what if you are unsure of the N? This is a situation where we can use fold expressions.

#include<iostream>

template<typename... Args>
auto sum(Args... arg)
{
    return (arg + ... );
}

int main()
{
    int total = sum(1, 2, 3, 4);
    std::cout<<"Sum = " << total;
    return 0;
}

The expression follows left associativity if the folding expression is used as (... +arg ) and right associativity if it is used as (arg + ... );





14 views0 comments

Recent Posts

See All

We can use variadic arguments to create variadic data structures in C++. template<typename ... T> struct DS{}; template<typename T, typename ... Args> struct DS<T, Args ...> { T first; DS<Arg

C++ standard library has simple functions to manipulate types. The following example shows how we can find the type of a variable and create new types using that. int main() { const double A = 10;

Constexpr is a keyword that declares that the value of a variable or a function is declared at compile time. Similar to the const keyword a compiler error is raised when any code attempts to modify th