r/cpp • • Jun 09 '26

Why we put chat messages in Redis streams (and plan to move old ones to MySQL)

11 Upvotes

The BoostServerTech Chat project stores every message in Redis. An in-memory data store that Rubén Pérez (@anarthal) already knows will need to be replaced for older messages down the road.

He did it anyway. Here's why and what the code looks like.

Rubén is the author of Boost.MySQL and co-maintainer of Boost.Redis. He built this chat server as a case study in composing Boost libraries for a real application.

The fit

Chat messages have a specific access pattern: append only, read backward (newest first), scoped to a room. Redis streams match this almost exactly. Each room (chat group) is a stream. Writing a message is XADD. Reading history is XREVRANGE. Redis assigns each entry a unique, time ordered ID, so you get message ordering and cursor-based pagination for free. No schema migrations, indexing decisions, or ORM.

A SQL table could do this. But messages are generated at a fast pace and most SQL databases would struggle with this insertion heavy flow. It would require serious performance tuning for a workload that Redis handles natively.

Storing a message

When a user sends a message, the server appends it to the room's Redis stream. The "*" tells Redis to auto assign a stream ID:

// Compose the request. XADD appends to the room's stream
// and auto-assigns an ID.
redis::request req;
for (const auto& msg : messages)
    req.push("XADD", room_id, "*", "payload",
             serialize_redis_message(msg));
// Execute it. All XADDs go out in one round trip.
redis::generic_response res;
error_code ec;
co_await conn_.async_exec(req, res, asio::redirect_error(ec));

Three things worth noting:

  1. Multiple XADD commands get pushed into a single redis::request. Boost.Redis pipelines them over one connection, so even if a client sends several messages at once, it's one round trip.
  2. This is a C++20 coroutine. The co_await suspends until Redis responds, but the thread is free to handle other work while it waits.
  3. XADD accepts an arbitrary list of (key, value) string pairs. We are using a single key named “payload” that contains the message serialized as JSON. This allows arbitrary nesting.

Serialization without boilerplate

Each message is stored as a JSON payload inside the stream entry. The wire format is a simple struct:

struct redis_wire_message
{
    std::string_view content;
    std::int64_t timestamp;
    std::int64_t user_id;
};
BOOST_DESCRIBE_STRUCT(redis_wire_message, (), (content, timestamp, user_id))

That BOOST_DESCRIBE_STRUCT macro registers the struct's members for compile time reflection. Boost.JSON picks it up automatically: boost::json::value_from(msg) serializes it, boost::json::try_value_to<redis_wire_message>(jv) deserializes it. No hand-written to_json/from_json functions. Add a field to the struct and the serialization updates itself.

This is one of those spots where Boost libraries click together in a way that's hard to replicate with unrelated dependencies. Describe provides the reflection, JSON consumes it. Three lines replace what would otherwise be two hand maintained serialization functions.

The tradeoff

Redis keeps everything in memory. That's what makes it fast, and it's also the obvious problem. Right now, the server runs with Redis persistence enabled, so data survives restarts. But as message volume grows, keeping the full history in RAM stops making sense.

The plan is to eventually offload old messages to MySQL for archival. The message layer is already isolated behind its own service interface, so swapping in a tiered storage strategy (recent messages from Redis, older ones from MySQL) touches one component. Nothing else needs to know.

But "eventually" involves a lot. The migration boundary is full of questions. Do you move messages after a time window? After a count threshold? Do you do it inline during reads, or as a background job? What happens to cursor based pagination when the data lives in two places?

If you've built a system that migrated data from a fast ephemeral store to a slower durable one, what triggered the migration and what surprised you about it? Rubén is interested in hearing what actually worked.


r/cpp • • Jun 08 '26 Popcorn

I built an ECS framework using C++26 static reflection features.

113 Upvotes

Hey all! Lately, I've been experimenting with C++26 static reflection features using Bloomberg's clang-p2996 compiler fork. I've tried a few different ideas, but this project has definitely been the most exciting for me.

The goal was to build an ECS framework that completely eliminates boilerplate setup. Things like manual component registration, system scheduling, and etc...After a few iterations and millions of demonic consteval errors, I've finally gotten it to a state where I feel like I can share it with public.

Here is RECS (Reflected Entity Component System)
https://github.com/bestofact/recs

Since this relies heavily on P2996, it's highly experimental, but it’s been a really nice exercise in pushing meta programming to its limits. Would be really nice to hear your thoughts on the RECS or any general feedback on the code.


r/cpp • • Jun 08 '26

New C++ Conference Videos Released This Month - June 2026

28 Upvotes

C++Online

2026-06-01 - 2026-06-07

ADC

2026-06-01 - 2026-06-07

CppCon

2026-06-01 - 2026-06-07


r/cpp • • Jun 07 '26

Your stdlib implementation matters more than the dispatch pattern

Thumbnail shubhankar-gambhir.github.io
149 Upvotes

A few weeks ago I posted about why std::variant + std::visit can be slower than a vtable and got called out for benchmarking on GCC 11. So I went back and reran everything across GCC 9 through 15. std::variant went from 28% slower than virtual on GCC 11 to 40% faster on GCC 12. I spent a while reading through libstdc++'s variant header to understand what changed. GCC 12 swapped the function pointer table in std::visit for a switch when there are 11 or fewer alternatives. The posts dig into how each stdlib handles visit dispatch.


r/cpp • • Jun 07 '26

Tobias Hieta: A Brief Overview of the LLVM Architecture

Thumbnail youtu.be
44 Upvotes

Tobias, a release manager for the LLVM project, walks us through the LLVM compiler pipeline using a single concrete C++ example, tracing it step by step from source code to machine assembly.


r/cpp • • Jun 07 '26

Parsing Expression Grammar Template Library (PEGTL) 4.0.0 Released

37 Upvotes

Hello, version 4.0.0 of the PEGTL has been released!

For those not familiar, let me quote the first sentence of the documentation: "The Parsing Expression Grammar Template Library (PEGTL) is a zero-dependency C++ header-only parser combinator library for creating parsers according to a Parsing Expression Grammar (PEG)."

The basics are still the same, grammars are implemented in C++ with nested template instantiations, however a lot has also changed. Some highlights:

  • Switched to Boost Software License
  • A bunch of new parsing rules and actions.
  • The inputs have been rewritten from scratch.
  • Nested exceptions are used for nested parsing errors.
  • Native support for parsing sequences of arbitrary objects (e.g. tokens).

This is the last major version that will stick with C++17.

Repository page: https://github.com/taocpp/PEGTL

Release page: https://github.com/taocpp/PEGTL/releases/tag/4.0.0


r/cpp • • Jun 07 '26

Performance Battle: Mutex vs CAS vs TAS vs Intel TSX

37 Upvotes

Performance Battle:

Mutex vs CAS vs TAS vs Intel TSX

std::mutex: A standard C++ lock object that provides mutual exclusion between threads.

CAS (Compare-And-Swap): An atomic operation that updates a memory location only if its current value matches an expected value.

TAS (Test-And-Set): An atomic operation that reads and sets a value simultaneously.

Intel TSX (Transactional Synchronization Extensions): An Intel technology that uses hardware transactional memory to reduce lock contention.

The following algorithm uses multiple threads to add 1 to a shared memory variable kLoop times. In this case, the sum of sum_atomic and sum_critical_section will be equal to kLoop. Although this is a highly inefficient algorithm, let's just accept it. (just for fun!)

int sum_critical_section;
std::atomic<int> sum_atomic;

void Thread() {
    constexpr auto kLoop{ 2200'0000 };
    constexpr auto kNumThread{ 88 };
    
    for (int i = 0; i < kLoop / kNumThread; ++i) {
        if (TryAcquire()) {
            sum_critical_section += 1;
            Release();
        } else {
            sum_atomic.fetch_add(1, std::memory_order::relaxed);
        }

        Idle(idle_time);
    }
}

An idle period was inserted between work units to control the level of contention.

(high contention: 0.6 us / low contention: 3.0 us)

TryAcquire are implemented as follows.

  1. Mutex

return mx.try_lock();

2. CAS

return not atomic_bool.load(std::memory_order::relaxed) and
atomic_bool.compare_exchange_strong(expected, true, std::memory_order::acquire, std::memory_order::relaxed)); // expected = false

3. TAS

return not (atomic_flag.test(std::memory_order::relaxed) or atomic_flag.test_and_set(std::memory_order::acquire));

4. Intel TSX

return _xbegin() == _XBEGIN_STARTED;

For both CAS and TAS, the lock variable is checked before attempting the atomic operation. If the lock is already set (true), the function immediately returns false without performing the CAS or TAS operation. Otherwise, performance will degrade.

System Description

CPU2 × Intel Xeon E5-2696 v4 (total 88-thread)
BuildC++23, g++ 13.3.0, -Ofast
OSUbuntu Server 24.04

The experiments were conducted on a two-node NUMA system. Accordingly, both sum_critical_section and sum_atomic were split into two separate counters.

Which of these four approaches do you think will win: Mutex, CAS, TAS, or Intel TSX?

Let's keep the rules simple: the winner is whichever finishes the workload the fastest.

.

.

.

.

.
.

.

.

High Contention: idle time = 0.6 us

Algorithmsum_critical_sectionsum_atomicelapsed seconds
Mutex1.04M21.0M0.521
CAS2.06M19.9M0.333
TAS2.00M20.0M0.335
TSX746K21.2M0.492

Low Contention: idle time = 3.0 us

Algorithmsum_critical_sectionsum_atomicelapsed seconds
Mutex6.93M15.1M1.216
CAS8.51M13.5M1.122
TAS8.61M13.4M1.107
TSX10.2M11.7M1.142

The winners of this benchmark are CAS and TAS

Of course, a benchmark win doesn't automatically make CAS or TAS superior in every situation. That said, it did win this round.

What are your thoughts on this matchup?

Errata (2026-06-08, 01:50 UTC):
Sorry!
I mentioned that, in the 2-node NUMA environment, I separated sum_critical_section and sum_atomic into two instances. However, I forgot to split the lock variables used for the mutex, CAS, and TAS implementations accordingly.

After rerunning the experiments, the winners are CAS and TAS.

=


r/cpp • • Jun 07 '26

Recent LLVM hash table improvements

Thumbnail maskray.me
83 Upvotes

r/cpp • • Jun 05 '26 Popcorn

The Story of C++: The World's Most Consequential Programming Language | The Official Story

Thumbnail youtu.be
430 Upvotes

r/cpp • • Jun 05 '26

More C++26 reflection at compile-time

Thumbnail andreasfertig.com
74 Upvotes

r/cpp • • Jun 04 '26

PSA - Do not assign the result of `::getenv` to a `std::string`

215 Upvotes

This is a lesson I apparently have to learn repeatedly. Many, many times. Way too many times.

Unit tests are failing, I'm too ADD to actually read the error message for comprehension, fart around changing things to try to find why the exception is being thrown, then spontaneously remember "oh, yeah, ::getenv will return NULL if the variable hasn't been defined, and assigning a NULL to a std::string is Bad Juju.

Wasted a whole day on this nonsense.

I know this. I have known this for years, and I still make this mistake.

Blah. Needed to vent.

Edit: Since this question has come up, no, I couldn't run it in a debugger. This was an automated build running under Jenkins following a push to Bitbucket, so all I had to go by was output from the build script and test harness. An uncaught exception was being thrown and the message said that NULL was not allowed in a string constructor, but no information as to where it was happening.

I couldn't reproduce the issue on the dev system because all the environment variables were defined there, so it took a while to put two and two together.


r/cpp • • Jun 04 '26

Rotation revisited: A shocking discovery about gcc’s unidirectional rotation algorithm

Thumbnail devblogs.microsoft.com
41 Upvotes

r/cpp • • Jun 04 '26

Do concepts improve deducing this?

Thumbnail meetingcpp.com
25 Upvotes

r/cpp • • Jun 04 '26

I spent a month optimizing my epoll based HTTP server from 15k req/sec to 125k req/sec

111 Upvotes

Greetings to my fellow nerds.

A month ago, I had zero network programming experience. So I decided to fix that by building an epoll based HTTP server from scratch and benchmarked every major architectural change along the way.

Performance Benchmarks :

  • Benchmark command : wrk -t4 -c10000 -d10s http://127.0.0.1:8080/
  • Request: GET /index.html
  • Response: Static HTML file (~1500 bytes)
  • CPU: Intel i5-13420H (13th Gen)
  • Compiler: Clang (O3)
ArchitectureThroughput (req/sec)Description
Blocking~15kSingle threaded blocking accept/read/write
Epoll (LT)~34kSingle threaded event loop utilizing non blocking I/O multiplexing
Epoll (LT, keep alive)~37.5kSingle threaded event loop with persistent connections
Epoll (LT, keep alive, sendfile)~41kSingle threaded event loop with persistent connections and zero copy file serving
Epoll (LT, keep alive, sendfile, multithreading)~125kMultithreaded architecture running 4 concurrent epoll loops (optimal on test machine)

Some Surprising Observations :

  • sendfile mattered less than I expected... for a server whose entire purpose is to serve files, I was expecting a bigger gain but maybe because my file was only ~1.5KB, it did not help much.
  • More threads made things worse :
Worker ThreadsThroughput (req/sec)
1~40k
2~95k
3~115k
4~125k
5~90k
6~90k
8~75k
10~70k
12~65k

My CPU has 6 physical cores and 12 logical processors, I suspect that the cost of all the syscalls for every loop, context switching, and lock contention on shared kernel objects, dominated on higher thread counts. Though I havent fully investigated it yet.

Profiling with perf :

FunctionApprox. CPU Samples
readSock()~22%
writeSock()~16%
parse()~8%
std::format()~7%
open()~3%
sendfile()~2.5%

Turns out Im still spending more time reading and parsing requests than sending responses, meaning there might still be room for batched reads or buffer pooling in a future iteration...

Final Thoughts :

I could hunt for possible micro optimizations or even experiment with an edge triggered architecture but im kinda burnt out at this point and this feels like a great point to end this project...

The codebase is pretty small (~1k LOC), so if anyone's interested in taking a look : https://github.com/Raju1173/epoll-http-server


r/cpp • • Jun 04 '26

consteig. How much math can you force the compiler to do at compile time? (a lot)

70 Upvotes

consteig src

consteig docs

Presented here is a header-only C++ compile-time eigenvalue and eigenvector solver with no dependencies beyond a C++17 compatible compiler (so no stdlib dependency, no .cpp files). I started on this project 6 years ago and only got back into finishing it recently.

Technically this is a "personal project" I suppose but I intend it to be used by other C++ programmers (or math nerds) and I'd consider it "production-quality". So I think a formal post is acceptable.

If you don’t remember (or haven’t encountered) eigenvalues/vectors, eigenvectors are vectors whose directions are unchanged when linear transforms are applied to the system (which makes them special). Eigenvalues are the factors by which an eigenvector is stretched or shrunk (but whose direction remains unchanged); usually this is expressed as matrices in linear algebra. They’re useful for lots of engineering problems.

For a certain class of problems the matrix for which you want to find the eigenvalues/vectors doesn’t change, effectively making the eigenvalues/vectors constants. These are things like state space matrices for LTI systems, roots of a polynomial, structural dynamics, and some graph/network problems. I’ve got some examples in my docs. If you need the eigenvalues/vectors for those in a C++ program, what you do today is either (1) calculate them at run-time using something like Eigen or (2) calculate them in matlab/python and hard-code them into your program. I’ve pushed all of the math for doing that into compile-time using the compiler itself. This means you can define static matrices at compile time, and save the eigenvalues/vectors off as constants in memory without needing to spend any run-time cycles nor to independently track/calculate them with another tool.

Again; I’ve got examples above, but you can use this to do something like specify filter characteristics (sample rate, cut-off frequency, Order, etc...) and at compile time calculate all the digital filter coefficients. So you can end up doing something like:

// 3rd order butterworth with 100Hz cut-off and 1kHz sample rate
static constexpr constfilt::Butterworth<double, 3> b(100.0, 1000.0);

//Call at 1kHz at run-time
b(new_sample);

And you never need to use python nor matlab to figure out what those coefficients are. I’ve also got another less-polished / less-tested / less-complete compile-time library called constfilt now that does exactly that. consteig available on GitHub and in vcpkg; I’m working on Conan :).


r/cpp • • Jun 03 '26

Why C++26 Contracts might not work for all

Thumbnail a4z.noexcept.dev
95 Upvotes

C++26 contracts are useful, but I don't think they're a universal replacement, or addition, for existing defensive programming checks. Here are some reasons why.


r/cpp • • Jun 03 '26

proof of concept c++ runtime & standard library

Thumbnail github.com
24 Upvotes

I've been hanging and experimenting around modern C++ and got plenty of ideas of how c++ standard library could look like. Of course, it sounds like another "c++ stdlib replacement", but see, i think found interesting solutions that could be interesting to you all.

The goal was to make a framework that expects a modern c++ code and compiles it to a very lightweight binary. for example, this code:

import std.io;

int main() {
    println("Hello, World");
    return 0;
}

Compiles to a tiny statically linked 576 byte executable. It does not link either to libc or libstdc++, using a custom runtime (instead of crt), written in fasm.

Another example is an echo server (executable size is 1312 bytes):

import std.io;
import std.net;
import std.string;
import std.view;

int main() {
    int sfd = socket(af_inet, sock_stream, 0)
        .expect("could not create socket");

    setsockopt(sfd, sol_socket, so_reuseaddr, 1)
        .expect("could not set so_reuseaddr");

    /* host -> network byte order is done at sockaddr_in constructor */
    sockaddr_in addr = sockaddr_in(6767, 0);

    bind(sfd, addr)
        .expect("bind failed");

    listen(sfd, 1)
        .expect("listen failed");

    sockaddr_in peer_addr;
    int cfd = accept(sfd, peer_addr)
        .expect("accept failed");

    string buf = string(128);
    for (;;) {
        /* read(int, string &) overload sets string length to actual value returned by read */
        if (!read(cfd, buf) || size(buf) == 0)
            goto close;
        write(cfd, buf);
    }

close:
    close(cfd);
    close(sfd);

    return 0;
}

i

In both of the examples you can already see particular design choices:

  1. Modules are first class feature. they speed up compile time and are more convenient to use than headers
  2. Standard library functions are global, like in C
  3. Rust-like results instead of exeptions. every syscall wrapper substitutes actual syscalls and returns a struct with a union containing either value or an error (usually an unsigned integer enum)

You can read project philosophy and get more details in the project readme and see another examples here. Currently this project is nothing more than an experiment and just a compilation of some interesting ideas i got lately.


r/cpp • • Jun 04 '26

CppCon 2026 Cppcon

17 Upvotes

Hi everyone,

I received the HRT Cppcon scholarship, and I'm excited to attend the conference and to those who attended as students, I'm curious about your experience!

Is it a good opportunity to also network as well? I would love to get a job as a C++ developer in the near future.


r/cpp • • Jun 03 '26

C++ Performance Quiz - A small side project to test your intuition for slow code

Thumbnail quiz.cpp-perf.com
114 Upvotes

I have been working on this little side project in my spare time and finally ready to start putting it online.

It's a C++ Performance Quiz, covering a bunch of topics from algorithms to general unexpected performance gotchas. Every question includes a compiler explorer link so you can look at the actual machine code the compiler generated once you pick an answer.

The goal is for people to have fun and help build a bit of intuition about performance; answering correctly or incorrectly is not intended to reflect someone's skill.

All feedback is welcome.

EDIT: Thanks everyone for the feedback, I plan to address a bunch of the issues raised over the weekend.


r/cpp • • Jun 03 '26

I spent 6 months building a zero-std, header-only graphics ecosystem from scratch—including my own container library

128 Upvotes

Hi everyone,

I wanted to share a massive passion project I've been refining: micro-gl (and its sister libraries). I needed a lightweight vector graphics engine for constrained environments, but I wanted absolute control over memory and types. I ended up falling down a 6-month rabbit hole.

The Core Architecture:

  • Zero Standard Library (std::): No hidden allocations. To support this, I spent an intense 3 weeks writing my own standalone container library (micro-containers) featuring AVL trees, an array-backed LRU pool, and a linear-probing hash map sized entirely at compile time via templates.
  • Type-Agnostic Math: The entire rasterizer is templated. It can run on raw float, double, or custom fixed-point integer types (like Q formats) for microcontrollers without an FPU.
  • The Engine Stack:

    • micro-gl: CPU-bound rasterizer handling textures, gradients, and Porter-Duff blending.
    • micro-tess: A precision-agnostic polygon tessellator.
    • nitro-gl: An OpenGL implementation that compiles C++ shader object hierarchies into monolithic GLSL strings at runtime, cached via MurmurHash.

Everything is purely header-only, allocator-aware, and optimized for extreme cache locality.

Repositories are open-source here:

I would love to hear your thoughts on the template design and compile-time sizing strategies!


r/cpp • • Jun 03 '26

Rotation revisited: Another unidirectional algorithm

Thumbnail devblogs.microsoft.com
32 Upvotes

r/cpp • • Jun 03 '26

Björn Fahller: I talk too much

Thumbnail youtu.be
9 Upvotes

Follow Björn's C++ speaker journey, 10 years summarized in a few minutes.

And if you get interested in being a speaker, contact me! We are always looking for new faces at our Meetups, and who knows, as this talk shows, there are quite some interesting personal developments possible.


r/cpp • • Jun 02 '26

The countdown to the C++ documentary premiere has started!

Thumbnail youtube.com
75 Upvotes

Hi all, we've been working on a C++ documentary for the last many months and it'll finally premiere this Thursday (June 4th) at 7PM UTC! It'll be a live premiere so we will all watch together and Bjarne Stroustrup, Herb Sutter, Gabriel Dos Reis and others will be in the chat. Now's the time to air your frustrations or thank Bjarne for the career it gave you. 😉 Hope to see you there!


r/cpp • • Jun 02 '26

Exotic CRTP: Enforcing Strict Interfaces Without Friends Using C++23 Explicit Object Parameters

27 Upvotes

I’ve been experimenting with CRTP and ended up with a variation that enforces a strict interface/implementation boundary without friend declarations. The goal was to eliminate boilerplate I frequently encountered when trying to encapsulate derived class methods.

The key idea is using C++23 explicit object parameters this + a small access wrapper type so implementations can only be called through the interface layer.

That was about two and a half months ago. Since, I’ve taken the time to better understand it and write an article about it, which you can find below. As explained there, I refer to this approach as Exotic CRTP.


Example

// Reference example of the pattern  
// See: https://medium.com/@felixolivierdumas/exotic-crtp-rethinking-static-polymorphism-with-c-23-89f9e75e8ffd

#include <iostream>  
#include <type_traits>  
#include <utility>

namespace exotic {

template<typename From>  
struct crtp_access : From {};

template<typename T>  
constexpr decltype(auto) as_crtp(T&& obj) noexcept {  
    using crtp_access_t = crtp_access<std::remove_cvref_t<T>>;  
    return static_cast<crtp_access_t&&>(obj);  
}

}

struct Base {  
    void interface(this auto&& self) {  
        exotic::as_crtp(self).implementation();  
    }  
};

struct Derived : Base {  
    void implementation(this exotic::crtp_access<Derived> self) {  
        std::cout << "Derived implementation" << std::endl;  
    }  
};

int main() {  
    Derived d;

    d.interface(); // perfectly works

    // d.implementation(); -> doesn't work, Derived only allows .interface()  
}  

UPDATE: I’ve reworked a big portion of the article to respond to the technical questions and feedback from here. It’s a pretty long read, but I’ve put a lot of effort into it, and I think it’s worth it if you’re interested in the topic.


Outdated but somehow valid explanation:

As many comments have mentioned, I'd like to clarify a few details regarding how the cast works.

Let's get straight to the point; the design is neither safe nor unsafe. Let me explain.

First of all, you need to know that the layout of structs/classes in C++ works as follows: in most ABIs, the Base Subobject of a Derived class (either a vtable pointer if polymorphic, or the complete object otherwise) is placed at the Derived's first address. Subsequently, the Derived's data (object) is placed there. This allows for down/upcasting, for example, because the compiler can simply cut the Derived portion to obtain the base, and vice versa.

This layout is not guaranteed by the standard. As I explained, it works with the vast majority of compilers, but there's no absolute certainty that this is how it’s going to appear. I must also reiterate that what I'm presenting today is closer to experimentation and a proof of concept than a finished product. It's an interesting concept; now all that remains is to develop it further.

So why am I explaining this? Because it's precisely with this mechanism that I can explain what happens during the cast to crtp_access<T>. Indeed, if we look closely at crtp_access<T>, we can see that it's empty. Therefore, if it inherits from any database (non-virtual; the design doesn't work if there's virtual inheritance in the chain), we can agree that its size will be equal to sizeof(T) + sizeof(crtp_access<T>), which is 0. This means that in memory, crtp_access<T> is exactly the same size as T. In addition to being the same size as T, in memory it is literally identical to it.

So, when we cast from T to crtp_access<T>, we are indeed performing an 'unsafe' cast, but it's still OK because it's as if we were casting from T to T. It's hacky, I admit, but I like to have fun and test things out.

So, design-wise, I agree that it's very hacky. However, I stand by my point that it's not unsafe ONLY in this specific case.

Also, thank you for all your comments. I've taken a lot of advice and it's helped me better understand my own design. I still have a lot to learn and I'm working on it every day. It's moments like these, when I spend four hours reanalyzing my pattern, that push me to improve even more!


Here’s the link to the article, it’s a long read (about 5,000 words, ~20 minutes), but I think it’s worth it if you’re into the topic: https://medium.com/@felixolivierdumas/exotic-crtp-rethinking-static-polymorphism-with-c-23-89f9e75e8ffd

Also, here’s a GitHub repo for those who would like to suggest improvements or modifications: https://github.com/unrays/exotic-crtp