Skip to content
C++Tipsand other shenanigans

Recent posts

Which comes first - int or float?

Clang now has an answer for you: it depends™

C++26 introduced std::type_order from P2830 to answer this very question. GCC has had support for it for quite a while; now Clang does too. Earlier today I merged the required changes to libc++. My implementation of the underlying builtin used to implement this was merged into Clang about two weeks ago.

So, why would you compare types in the first place and what does “it depends” mean?

[…]
Read update

Tips

01

Are your maps allocating unnecessarily?

Consider a map with a std::string as the key type, for example mapping an HTTP route to its handler:

std::unordered_map<std::string, Handler const*> handlers;

What actually happens when you try to look things up in this map? Let’s say that you want to test it with handlers.find("/api/v2/accounts/positions/summary"). This code will compile and run quite happily, but under the hood this allocates the literal into an entirely new std::string object, hashes it, finds the value, and then throws the temporary string away.

Read more
02

Can you subscript tuples?

In C++ tuples are implemented as library feature rather than as language feature. As a consequence of that, we are syntactically limited by what the language offers.

This means rather than being able to subscript tuples directly, we need to use std::get<N>(tup) instead.

So… if we step a bit outside of the boundaries of the standard, can we subscript instead?

auto tup = nonstd::tuple(1, 'c', 3.2);
f(tup[0], tup[2]);
Read more
03

Your compiler complains you're not in template context?

This can happen if you attempt to use P1061 pack-introducing structured bindings outside of a template:

void f() {
// error: pack declaration outside of template
auto [...Is] = expr;
}

To avoid turning f itself into a template, you can use P1306 expansion statements. Unlike lambda solutions, this does not push another function scope.

Read more

Articles

Variadic Switch

Generating efficient switch-like dispatch from parameter packs, from function tables and macros through folds and C++26 expansion statements.

C++26 Expansion Tricks

Exploring C++26 expansion statements, the expand pattern, and structured bindings for turning compile-time ranges into packs.

Fun with C++26 reflection - Keyword Arguments

Implementing keyword arguments in C++ by abusing reflection.

Updates

    1. Which comes first - int or float?

      C++26 std::type_order provides an implementation-defined total ordering of types, enabling simpler canonicalization and deduplication. Now you can use it.

PydongWrong language? How about Python shenanigans instead?