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 »
Jonathan

Tutorial: C++20’s Iterator Sentinels

You probably know that C++20 adds ranges. Finally we can write copy(container, dest) instead of copy(container.begin(), container.end(), dest)!

Ranges also do a lot more. Among other things, they add a new way of specifying an iterator to the end – sentinels.

» read more »
Jonathan

Naming Things: Implementer vs. User Names

I wanted to write this blog post about (a specific part of) naming things back in July, but ironically I didn’t have a name for the symptom I wanted to describe. I only found a good name when I attended Kate Gregory’s talk on naming at CppCon, and now I finally have the time to write my thoughts down.

So I want to write about naming. In particular, about the phenomenon that sometimes a name is a perfect description of what a function does, yet it is totally useless.

» read more »
Jonathan