Nifty Fold Expression Tricks--Jonathan Müller

Many things can be done!

Nifty Fold Expression Tricks

by Jonathan Müller

From the article:

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...

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.