Nifty Fold Expression Tricks
Suppose you need to have a variadic function and want to add all arguments together. Before C++17, you need two pseudo-recursive functions:
template <typename H, typename ... T>
auto add(H head, T... tail)
{
return head + add(tail...);
}
template <typename H>
auto add(H head)
{
return head;
}
However, C++17 added fold expressions, making it a one-liner:
template <typename H, typename ... T>
auto add(H head, T... tail)
{
return (head + ... + tail);
// expands to: head + tail[0] + tail[1] + ...
}
If we’re willing to abuse operator evaluation rules and fold expressions, we can do a lot more. This blog posts collects useful tricks.
» read more »