Reflecting JSON into C++ Objects -- Barry Revzin
C++26 marks a transformative milestone with the adoption of full compile-time reflection, enabling powerful new metaprogramming capabilities. In this post, we’ll explore how reflection lets you turn a JSON file directly into a fully-typed C++ object — all at compile time.
Reflecting JSON into C++ Objects
by Barry Revzin
From the article:
Last week, C++26 was finalized in Sofia, Bulgaria — and C++26 will include all of the reflection papers that we were pushing for:
- P2996R13: Reflection for C++26
- P3394R4: Annotations for Reflection
- P3293R3: Splicing a Base Class Subobject
- P3491R3:
define_static_{string,object,array}
- P1306R5: Expansion Statements
- P3096R12: Function Parameter Reflection in Reflection for C++26
- P3560R2: Error Handling in Reflection
Those are in the order in which they were adopted, not in the order of their impact (otherwise splicing base classes would go last). This is a pretty incredible achievement that couldn’t have happened without lots of people’s work, but no one person is more responsible for Reflection in C++26 than Dan Katz.
So today I wanted to talk about a very cool example that Dan put together on the flight home from Sofia, while I was unconscious a few seats over: the ability to, at compile time, ingest a JSON file and turn it into a C++ object. That is, given a file
test.json
that looks like this:{ "outer": "text", "inner": { "field": "yes", "number": 2996 } }
We can write this:
constexpr const char data[] = { #embed "test.json" , 0 }; constexpr auto v = json_to_object<data>;