C++26 Reflection!
06 Jan 2025
I have a lot of thoughts about things, but I generally don't voice most of them, for better or for worse. I do want to voice this thought though, the thought of reflection in C++. I think it will be amazing.
Because this paper is constantly changing and evolving, this post is only relevant/correct for revision 8 of the proposal, as it is the most up-to-date as of the time of writing.
C++ doesn't inherently need reflection (well, C doesn't), because it's statically typed. The types are available at compile-time, so if you know the types then why are you wanting to introspect them? Truth is, it's not that simple. Pointers exist, meaning you can point to data that may not exist yet, data that you may not know the type of (this is in C too, the void pointer). This, generally, only happens with polymorphism in C++ (at runtime anyway). Although this method of reflection is not runtime, so it will not help with whatever problems you're experiencing if you're trying to get RunTime Type Information (although, to be honest, if you find yourself needing RTTI a lot, you either have some insane setup like Unreal Engine, or you maybe have a less-than-ideal architecture. Just a thought). What it will help with, however, is template parameters, enumeration to string and back conversions, and more general QoL things (less yucky macro code!).
Try it yourself
Before we start, you can try reflection yourself on Compiler explorer. To my knowledge, only Nvidia's nvc++ (which I believe uses EDG, which also supports reflection and is more up-to-date than nvc++), and a fork of Clang (x86-64 clang (experimental P2996) on Compiler Explorer) have implementations. To use nvc++, you need x86 nvc++ 24.11 and -std=c++23 --reflection compile options. Here's links to those, just for you:
- EDG (most up-to-date with the proposal)
- nvc++ (does not yet support new reflection operator
^^) - Clang (doesn't work too well, not sure what's up with that)
The Reflection Domain
I thought I'd start this post off with a small introduction to the "reflection domain" (as opposed to the "grammatical domain" that we're so used to coding in). This is the space where the std::meta::info type lives. It's an interesting place, and I suppose can be thought of as what a pointer is to the type it's pointing to, the reflection domain is to whatever code it is reflecting. To get to the reflection domain, you must "lift" something in your code up there, via the double caret ^^ (reflection) operator (this was changed recently to double carets instead of a single caret ^ due to compatibility issues with Objective-C++ and Clang's block extension). This turns that "thing" into an std::meta::info value which holds the information that makes up that "thing". This variable can then be queried with the functions inside the std::meta namespace for certain things, like if it's a class, a class member, what its base classes are, if it's noexcept, const, what linkage it has, etc. More or less everything the compiler might know about that "thing" (because it is compile-time only). These functions are all consteval, to keep with the compile-time theme. You cannot use them at runtime, so naturally, the std::meta::info type is completely useless at runtime.
Back to the Grammatical Domain
OK, that's great, but how does one get back down from the reflection domain? By using something called the splicer. The splicer takes a reflected value and converts it back to the grammatical domain. Think of this almost as de-pointering a variable. Almost. Splicing allows you to use a reflected value anywhere that whatever it's reflecting would normally be used (with some additions in places, but we'll get there in a bit).
Syntax
Now to introduce the syntax! This example is taken from the P2996 paper (rev. 8), which proposes the whole reflection stuff:
constexpr auto r = ^^int;
typename[:r:] x = 42;
typename[:^^char:] c = '*';
Let's break it down:
constexpr auto r = ^^int;
This line "lifts" the type int into the reflection domain, returning the type std::meta::info (auto is used here for brevity). It's constexpr because it doesn't need to change, and can be compile-time.
Great, now that we have a variable of type std::meta::info that holds int's information, we can use it in things, like bringing it back into the grammatical domain to declare a new variable:
typename[:r:] x = 42;
This declares a variable x of type typename[:r:], which is spliced r. This whole line is equivalent to:
int x = 42;
Now, it is a bit stupid to go around replacing types with their spliced reflected counterparts everywhere, but it's an example so bare with me. typename is used here, I believe, to help with the parser. It "can be omitted in the same contexts as with dependent qualified names" - 3.1 "Back-And-Forth" (p2996r8). What this actually means, is that typename doesn't need to used in locations where it's obvious to the parser that what's coming next is a type, like in aliases (using MyType = [:r:]), templates (std::vector<[:r:]>), etc. I think anyway. typename is used here, as lots of things could exist after a ;.
typename[:^^char:] c = '*';
This is just an example of reflecting a type, then immediately splicing it. Equivalent to:
char c = '*';
So quite useless on its own (probably).
Making it useful
So far, there's only been simple examples. Nothing that actually helps the average C++ programmer. UNTIL NOW!
INTRODUCING, FOR THE FIRST TIME EVER (not really), EASY, SIMPLE ENUM TO STRING CONVERSIONS!
Picture this, you want to turn an enum into a string. Your intent behind this is the take the name of the specific enumerator inside the enumeration, and have the string representation of that, not to take its value and convert that into a string (that's already quite easy!). You couldn't do this until now without some external library, like Magic Enum. The problem with this, is that it's an external library. That and it uses a compiler hack, which isn't super ideal. Reflection would be part of the language itself, so no hack needed!
OK, I've hyped you up enough, here's how it looks in use:
enum class EMyEnum {First, Second, Third};
constexpr std::string val {enum_to_string(EMyEnum::Second)}; // val == "Second"
This is great! Here's the implementation, from the p2996 paper (with added comments to explain what's happening):
template<typename E>
requires std::is_enum_v<E> // type_trait with C++20 requires to prevent non-enum types
constexpr std::string enum_to_string(E value)
{
// "template for" is a not-yet-standard compile-time for loop (like "if constexpr")
// loop over the enumerators of the enum type (EMyEnum::First, EMyEnum::Second, etc.)
template for (constexpr auto e : std::meta::enumerators_of(^^E))
{
// if the value to convert to string == the splice of the reflection of E's enumerator
// equivalent to (if at the second enumerator that is):
// if (value == EMyEnum::Second)
if (value == [:e:])
{
// return the "identifier" of the reflection of the enumerator (its name)
return std::string(std::meta::identifier_of(e));
}
}
// the input enumerator value did not match any of the enumerators in the E enum
// this really shouldn't be getting hit
return "<unnamed>";
}
Hopefully the comments clear up the questions you might have. One big thing about this is that, even in the compilers that implement reflection, it won't compile, because template for isn't valid (yet anyway). It's just used here as if it were standard for simplicity. The alternative (which does compile) is like so:
[:expand(/* some range */):] >> /* lambda to call for each iteration */;
This is implemented in the paper at 2.3 "Implementation Status". Changing the enum_to_string function to use expand() looks like so (also taken from the paper):
template<typename E>
requires std::is_enum_v<E>
constexpr std::string enum_to_string(E value)
{
std::string result = "<unnamed>";
[:expand(std::meta::enumerators_of(^^E)):] >> [&]<auto e>
{
if (value == [:e:])
{
result = std::meta::identifier_of(e);
}
};
return result;
}
As you can see, this doesn't actually look that bad (I can see how it might look like insanity, but really it isn't!!). It's just a slightly reformatted range-based for loop. Anyway, I personally prefer returning something like std::optional over a "<unnamed>" string, and yes it does work with std::optional, I tried it with the EDG compiler on Compiler Explorer. Here's the implementation of that by the way.
What next?
That's it for this blog post. But the applications for compile-time reflection are almost limitless. You could create a form of runtime reflection from it, with a constinit array of your own class structures, etc. You could implement a more user-friendly serialisation library, as getting a class' layout is much simpler with reflection. So many fun things, so little time!
I trust that this post was helpful, at least in part.