Generative C++
Channel: CoreCppIL
Date: 2022-12-08

Presented by Alon Wolf at Core C++ 2022.

Currently, there are two main ways to generate code in C++ - templates and macros. While macros can manipulate text, they lack the compile time information and constraints that the compiler provides. Templates on the other hand are incredibly powerful especially with C++20’s concepts, non type template parameters and increased constexpr support, however, while they work great with types and compile time constants they can't be used with identifiers, keywords and other C++ syntax elements. The metaclasses proposal by Herb Sutter aims to give more powerful code generation tools, but it is not part of the standard yet. We will also compare these features to code generation features in other languages. So what can we do right now in C++ in terms of generative code? Well... the answer is anything we want.

In this talk, we will go over a different approach for compile time code generation that can be used right now with C++ 20. We will use it to implement the examples from Herb Sutter's metaclasses talk, generate consistent C++ and vulkan shader code, and extend it to support arbitrary compile time execution (yes, it can even run minecraft).

We will cover key compile time development topics: 1. What are the pros and cons of the possible compile time input validation methods (static assert, constexpr throw, concepts) and which one should you choose for your compile time library. 2. Working in constexpr context and easily converting between dynamic containers (vector, string) and static containers (array). 3. Designing expressive APIs with non type template parameters.

To achieve our goal of code generation we will also dive into some less known topics like the behavior of std::source_location in templates, compile time printing of constexpr strings, DLL injection, function hooks and some pitfalls of C++20's modules build process and how to avoid them.

In the end you will have all the tools to create your own compile time code generation library or just download the library with the examples from GitHub and use it.

-----
Alon is a Senior Software Engineer at Medtronic specializing in 3D and computer graphics with a passion for high performance. He has developed many custom simulation and rendering engines for different platforms using modern C++. He also writes a C++ technical blog and participates in game jams.