Skip to content
C++Tipsand other shenanigans

Tips

Tips and tricks that didn't fill a proper long-form article

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
PydongWrong language? How about Python shenanigans instead?