Joseph
Fold Expression in C++17
Updated: Nov 9, 2022
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 + ... );