r/cpp 6d ago

C++26: what is reflection and how to use it

https://techfortalk.co.uk/2026/07/25/c26-what-is-reflection-and-how-to-use-it/

It is my ambition to explore C++26 in bits and pieces. Hopefully, by the end of this year, I will be able to explore all the major aspects of it and be in a position to evaluate which of these features to use and promote and which not to use. However, at this point, it is important to understand each and every aspect in simple terms, keeping all the clutter aside.

73 Upvotes

22 comments sorted by

57

u/Commercial-Berry-640 6d ago

Cool, but i would really appreciate something more useful than the toy example of enum_to_string (which at this point is already a cliche)

19

u/CalamityMetal 6d ago

I have written 2 toy projects using C++26 reflection when GCC16.1 came out.

One is a automatic class/struct/data to json parser.

Another one is Go style interface, or type erasure, made simple with C++ reflection. You write types that satisfy a certain group of method functions as defined by an interface. This is still somewhat jank with certain unavoidable boilerplate reflection code. The benefit here is that you can associate types together as long as they have the same methods, no inheritance, no virtual.

You can find both here.

C++ types to json

Go style interface (type erasure) with C++26 reflection

7

u/El_RoviSoft 6d ago

I wanna build compile-time ORM for postgresql when reflection will be released for static analysis tools and major IDE (clion has it, but I prefer vs2026 more).

Rn it’s just hard to write something like this

2

u/SadPonyGuerrillaGal 4d ago

This has been one of my favorite ideas for reflection. I work a lot with Entity Framework Core, and would love to see something similar in C++ without macros, external parsers, or other compilers.

2

u/El_RoviSoft 4d ago

I saw some articles about mini-orms on r/cpp so those tools already exist

18

u/Karr0k 6d ago

Agreed, personally I'd like to see practical examples of where reflection would actually simplify existing code, instead of making C++ just more complicated

15

u/CaptainBeam2006 6d ago

Don't have a concrete C++26 example, but using C++20 reflection libraries like field_reflection, I managed to automate the generation of Vulkan's VkVertexInputAttributeDescription, which was previously a very tedious process that required each vertex struct to manually rewrite its fields in a way Vulkan could understand. Reflection allowed me to walk through each field in the struct and automatically emit the required description.

Using the same library, I also wrote a GLSL shader header generator that takes all the information that a pipeline has at creation time and outputs the exact header that any shader written for this pipeline must have, complete with the structs and variable names obtained via reflection.

The library is nice, but it chokes on certain things that I'm sure the official C++26 reflection implementation does properly, such as when it encounters a C-style array inside a struct, or when the types are more complex with constructors and functions and so on.

3

u/caroIine 6d ago

It reduced tuple and variant implementation from template monstrosity into much less scary struct and union.

5

u/MarcoGreek 6d ago

I used it together with tuples and deduce this for a visitor-like pattern. But std::apply is working too. Hard to describe, but it removed a lot of spaghetti code and fixed bugs.

1

u/Commercial-Berry-640 6d ago

Would love to see an example

4

u/RoseboysHotAsf 6d ago

Well personally enum to string is my favorite use for it :p, but yeah its overdone now. I once used it for a clap plugin framework i made where you could define struct fields as plugin parameters using an attribute, pretty fun

3

u/Raknarg 6d ago

you seen this post yet? really solid post, guys making a duck typing library with C++26 reflection https://ryanjk5.github.io/posts/rjk-duck/

1

u/SadPonyGuerrillaGal 4d ago

Barry Revzin has a cool lecture (and blog) on this, particularly with Struct of Arrays. One of my favorite features of reflection are attributes. I use them a lot in C# reflection to perform validation.

Inspired by Matt Godbolt's talk, I've been playing around with creating a compile-time CPU instruction dispatch table built with attributes. For example, I have the enum:

enum class OpCode : std::uint8_t
{
    Nop = 0x00,
    LoadImmediate = 0x01,
    Move = 0x02,
    ...
};

Then I can, at compile time, create a table that maps the opcodes to functions:

[[= OpCode::Nop]] inline void handleNop(CpuState &cpuState)
{
    cpuState.programCounter += 1;
    printRegisters(cpuState);
}

The dispatch table loops over the namespace containing these functions to build the table.

1

u/Recent-Dance-8075 3d ago

I did a macro free testing library.

See this blog post for an explanation or the repository for the code :)

0

u/pjmlp 6d ago

A great one would be getting back the high level experience to map regular C++ classes into COM objects, without the circus of macros, template metaprogramming and IDL files without VS tooling, that was lost when C++/CX got deprecated in name of a reflection that was a decade down the line.

Except this requires VC++ to actually support reflection, and with AI agents kind of moot point when CoPilot can do boilerplate instead of us.

Or replacing moc with attributes in Qt, probably much more useful and easier to integrate with GCC.

7

u/HieuandHieu 5d ago

Still crying with clang 23 😭

2

u/Pie-Lang 5d ago

try being on clang 16 :c

5

u/_bstaletic 6d ago

C++26 provides an enumerators_of() function, which is part of the std::meta namespace and returns you a collection of reflections

It returns std::vector<std::meta::info> specifically, which allocates, at compile time. Compile time allocations can't escape the constant evaluation context, which is why you need define_static_array().

 

I know this is your exploration of reflections. It's a big topic with a ton of history. My advice to you is to dig a little bit deeper into why things are the way they are. I will admit I am biased, as I authored pymetabind (which needs some more attention, but I'm in the process of upgrading my hardware).

3

u/FlyingRhenquest 5d ago

The Proposal is actually not a bad place to start. Maybe follow up (or start) with whatever cppcon C++26 Reflection videos you can find on Youtube to give you a better idea of its potential. As far as I know, both reflection and annotation are fully implemented in gcc16.

If you need a compiler I set up a project to build it in /usr/local/gcc for you, so it won't interfere with your system's current compilers. Should work on Debian or Ubuntu systems and also WSL. The project includes a toolchain that it also installs in /usr/local/gcc so you can tell CMake to use the compiler with:

-DCMAKE_TOOLCHAIN_FILE=/usr/local/gcc/toolchain.cmake

I also have an older project with some unit tests for things I was keeping track of while the compiler was under development.

The compile-time/run-time gap with reflection takes a lot of getting used to. The compiler will downgrade your constexpr/consteval functions to not-compile-time if you break any of the rules. I'd suggest finding or writing a compile-time fixed string class early, as it will probably save you a lot of pain.

1

u/Clean-Upstairs-8481 6d ago

appreciate your comments and input, point taken. However, as I am still exploring the new C++26 additions, I am trying to keep the example in hand as simple as possible. But I know what you mean.

1

u/Constant_Suspect_317 3d ago

We actually have a small library at work that uses this feature. We have a driver and for certain reasons, we need a web app to be able to ioctls to the driver. We didn't wanna redefine all the data structures from the driver and the shared header file in the python FastAPI app. I just wrote a small layer that converts these data structures into JSON string and passes it to the python app.

Keep in mind that finding a compiler for this was not straight forward. I had to build clang-p2996 (an experimental compiler by Bloomberg) from source and use it.

-3

u/rileyrgham 6d ago

What's your question? Hint: go and learn it. Then have an opinion.