Articles & Books

Annotations for C++26 Hashing -- Krystian Piękoś

Static reflection already makes generic hashing in C++26 far more expressive, but annotations push it into genuinely ergonomic territory. By letting types explicitly opt-in to hashing and allowing individual members or base classes to be cleanly excluded, we get a solution that is both powerful and readable.

Annotations for C++26 Hashing

by Krystian Piękoś

From the article:

In my recent post, I demonstrated how to use static reflection from C++26 to implement generic hash computation for custom types. Let's review the final implementation. The core of the solution is the calculate_hash() function, which iterates over sub-objects (including both base classes sub-objects and class/struct non-static data members) to compute a combined hash.

template <typename T>
concept Hashable = requires {
  { std::hash<T>{}(std::declval<T>()) } -> std::convertible_to<size_t>;
};

template <typename T>
  requires std::is_class_v<T>
size_t calculate_hash(const T& obj, size_t seed = 0)
{
  constexpr auto ctx = std::meta::access_context::unchecked();

 
  static constexpr auto r_subobjects = std::define_static_array(std::meta::subobjects_of(^^T, ctx));

  template for (constexpr auto r_sub : r_subobjects)
  {
    using Subobject_t = typename[:std::meta::type_of(r_sub):];
    static_assert(Hashable<Subobject_t>, "Subobject must be hashable");
    Utility::hash_combine(seed, obj.[:r_sub:])
  }

  return seed;
}

How ref qualifiers led to deducing this

A follow up on last weeks post on ref qualifiers:

How ref qualifiers led to deducing this

by Jens Weller

From the article:

Last week I shared an overview on ref qualifiers with you, this is a follow up on this post. Featuring deducing this, a C++23 feature that should be available in your compiler if its been released in 2025 or later.

Lets start with two more things you may want to know about ref qualifiers. First, const is also supported for the rvalue version: m::f()const && exists, though this is mostly not very useful. Thats why you rarely see it covered, as const rvalues are unusual to unvalid. But thats where m::f()const&&=delete comes in, it allows you to turn these object states in to compilation errors.

As ref qualifiers are also often used...

 

C++26: Structured Bindings in Conditions -- Sandor Dargo

SANDOR_DARGO_ROUND.JPGStructured bindings in conditions may look like a small syntax sugar, but they let us write much more expressive conditional logic. By allowing decomposition and condition checking to live side by side, C++26 reduces boilerplate, improves locality, and better supports modern result types that bundle status and data together. This is a pragmatic, well-integrated evolution of a feature that has already proven its value since C++17.

C++26: Structured Bindings in Conditions

by Sandor Dargo

From the article:

Structured bindings were introduced in C++17 as an alternative way of declaring variables. They allow you to decompose an object into a set of named variables, where the collection of those bindings conceptually represents the original object as a whole.

// https://godbolt.org/z/97GaMajMP

#include <cassert> #include <string> 
struct MyStruct {
    int num;
    std::string text;

    bool operator==(const MyStruct&) const noexcept = default;
};

MyStruct foo() {
    return {42, "let's go"};
}

int main() {
    const auto& [n, t] = foo();
    MyStruct ms{n, t};
    assert(ms == foo());
    return 0;
}

Let the Compiler Check Your Units -- Wu Yongwei

logo.pngMixing your units can be disastrous. Wu Yongwei takes a quick look at C++ unit libraries that can help keep everything in order.

Let the Compiler Check Your Units

by Wu Yongwei

From the article:

I recently came across a C++ standard proposal P3045 [P3045R7], which aims to add physical units to C++. Curious, I looked into the existing unit libraries and went down quite a rabbit hole.

Type safety and user-defined literals

Before exploring these libraries, I was already somewhat familiar with the idea of ‘type safety’. I was also aware that user-defined literals (UDLs) [CppReference-1] allow creating literals of specific types with ease. Typical uses in the standard library include string/string_view literals and the chrono library [CppReference-2], which make code both convenient and safe.

Figure 1 shows some simple examples.

auto msg = "Hello "s + user_name;
auto t1 = chrono::steady_clock::now();
this_thread::sleep_for(500ms);
auto t2 = chrono::steady_clock::now();
auto duration = t2 - t1;
auto what = t1 + t2;      // Can't compile
cout << duration / 1.0ms; // To double, in ms

Exploring ref qualifiers in C++

Recently I've been wondering about ref qualifiers in C++.

Exploring ref qualifiers in C++

by Jens Weller

From the article:

Ref qualifiers are today an old C++11 feature, and recently I wanted to know more about them. Especially their potential use cases.

Thats a particular point with this feature, I've seen examples - but often without a compelling use case. This feature is a great way to achieve very specific things in C++...

 

What reinterpret_cast doesn't do -- Andreas Fertig

Depositphotos_347968346_S.jpgIn today's post, I will explain one of C++'s biggest pitfalls: reinterpret_cast. Another title for this post could be: This is not the cast you're looking for!

What reinterpret_cast doesn't do

Andreas Fertig

From the article:

My motivation for this blog post comes from multiple training classes I thought over the past several months and a couple of talks I gave. Since C++23, you have a new facility in the Standard Library: std::start_lifetime_as. When teaching class with a focus on embedded environments or presenting talks with such a focus, I started to add std::start_lifetime_as to the material. With an interesting outcome.

The feedback I get is roughly:

  • why do I need std::start_lifetime_as, I already have reinterpret_cast?
  • why can I use reinterpret_cast?

If you never heard of start_lifetime_as please consider reading my post, The correct way to do type punning in C++ - The second act.

What Happens When a Destructor Throws -- Sandor Dargo

SANDOR_DARGO_ROUND.JPGEven experienced C++ developers sometimes stumble on a deceptively simple question: what actually happens when a destructor throws an exception? This post breaks down the mechanics behind stack unwinding, noexcept, and why throwing from destructors is almost always a bad idea

What Happens When a Destructor Throws

by Sandor Dargo

From the article:

Recently I wrote about the importance of finding joy in our jobs on The Dev Ladder. Mastery and deep understanding are key elements in finding that joy, especially now that generating code is cheap and increasingly done better by AI than by us.

Then a memory surfaced. I frequently ask during interviews — as part of a code review exercise — what happens when a destructor throws. Way too many candidates, even those interviewing for senior positions, cannot answer the question. Most say it’s bad practice, but cannot explain why. Some say the program might terminate. Getting an elaborate answer is rare.

I’m not saying it’s a dealbreaker, but it definitely doesn’t help.

Let’s see what actually happens.

The role of a destructor

A destructor is the key to implementing the RAII idiom. RAII matters because after you acquire a resource, things might go south. A function might need to return early, or it might throw. Making sure resources are released is cumbersome, and the cleanest way to achieve it is to wrap both acquisition and release in an object that handles this automatically.

But what if the release itself is not successful?

Destructors have no return value, so error reporting is limited. Typical options include logging, storing error state, or (discouraged) throwing.

Why did I mark throwing an exception discouraged?

Evolving a Translation System with Reflection in C++

A nice example of C++26 reflection moving from theory into something practical.

Evolving a Translation System with Reflection in C++

By GitHub user: friedkeenan
 

From the post:

Lately, I’ve been using C++26 reflection to create some crazy and cursed stuff. But even though I quite enjoy that work, it is as well quite far from the norm of what reflection is going to offer us in our everyday code.

Reflection is definitely not just that craziness, and so I want to present reflection in a more grounded environment, and in a way that will probably land as more typical usage as our codebases gradually come into contact with it.

So then, in this blogpost, I will be exploring a spectrum of options for how reflection can upgrade a translation system that I already use in one of my projects. We’ll look at where it’s at now without reflection, identify places in which reflection could plausibly help, and then explore a series of modifications we could make to soothe those problem points.

The purpose of looking at each of these options will not be to declare that one is clearly the best option or the one that makes the most sense, but rather to get a better feel for what could make sense to do, and whether some things are really worth the effort. We’re trying to gauge the benefits that reflection can bring to our code.

And who knows, even if one option is less appealing for this particular situation, maybe in a different situation it could be the perfect fit.

C++26: A User-Friendly assert() macro -- Sandor Dargo

SANDOR_DARGO_ROUND.JPGC++26 is bringing some long-overdue changes to assert(). But why are those changes needed? And when do we actually use assert, anyway?

At its core, assert() exists to validate runtime conditions. If the given expression evaluates to false, the program aborts. I’m almost certain you’ve used it before — at work, in personal projects, or at the very least in examples and code snippets.

So what’s the problem?

C++26: A User-Friendly assert() macro

by Sandor Dargo

From the article:

assert() is a macro — and a slightly sneaky one at that. Its name is written in lowercase, so it doesn’t follow the usual SCREAMING_SNAKE_CASE convention we associate with macros. There’s a good chance you’ve been using it for years without ever thinking about its macro nature.

Macros, of course, aren’t particularly popular among modern C++ developers. But the issue here isn’t the usual - but valid - “macros are evil” argument. The real problem is more specific:

The preprocessor only understands parentheses for grouping. It does not understand other C++ syntax such as template angle brackets or brace-initialization.

As a result, several otherwise perfectly valid-looking assertions fail to compile:

// https://godbolt.org/z/9sqM7PvWh
using Int = int;
int x = 1, y = 2;

assert(std::is_same<int, Int>::value);
assert([x, y]() { return x < y; }() == 1);
assert(std::vector<int>{1, 2, 3}.size() == 3);
 

 

Stackless coroutines for gamedev in ~200 lines of C++ -- Vittorio Romeo

C++20 coroutines have lovely syntax, but they're a terrible fit for games.

In this article, we'll build a macro-base alternative that's more suitable for game development in ~200 lines of C++.

Stackless coroutines for gamedev in ~200 lines of C++

by Vittorio Romeo

From the article:

For a game I want a coroutine that is part of an object’s data. When the object dies, the coroutine dies with it. When I serialize the object to a save buffer, the coroutine’s state goes with it. When the optimizer is off, there is no extra cost compared to the equivalent state machine. C++20 coroutines do not provide any of these guarantees out of the box.

Let’s build something that does.