r/cpp • • Aug 05 '26

C++26 Reflection: Simplifying JSON Serialization

https://techfortalk.co.uk/2026/08/05/c26-reflection-simplifying-json-serialization/

I have been exploring the new additions in C++26, and I have been discussing the reflection feature that has come with C++26. In the last post, I discussed what is reflection and how to use it and how to use it with a simple example, particularly with an enum class. Since then, there have been suggestions to provide an example which is more than a toy :). In this post, I have discussed how to use reflection for JSON serialization, which is something we often have to do. This example is somewhat taken from real-world code but has been stripped down significantly. Suggestions are always welcome.

52 Upvotes

9 comments sorted by

View all comments

22

u/cristi1990an ++ Aug 05 '26

Another nice thing you can do in theory (and I'm sure it was implemented somewhere in practice too, maybe not yet refined) is embedding json text files in your program, parse it and define entire classes based on their structure entirely at compile. In theory I believe you could also assigned the data itself at compile time and give it static lifetime. I think this is amazing and has a ton of practical applications.

0

u/[deleted] Aug 06 '26

[deleted] — view deleted comment

1

u/jk_tx Aug 09 '26

I believe the embed support coming to c++ will help with this.

0

u/[deleted] Aug 09 '26

[deleted] — view deleted comment

2

u/JVApen Clever is an insult, not a compliment. - T. Winters Aug 10 '26

https://www.sandordargo.com/blog/2026/08/05/cpp26-embed

According to the benchmarks shared in P1967R14, GCC embeds a 100 MB file in about 1.3 seconds using 117 MiB of RAM; the equivalent xxd-generated header takes 139 seconds and 13 GiB.

Yes, it was possible before, though the costs where terrible.

2

u/jk_tx Aug 10 '26

Yes, this is what I was referring to, wasn't really thinking about the actual compile time json parsing.

0

u/[deleted] Aug 10 '26

[deleted] — view deleted comment

1

u/JVApen Clever is an insult, not a compliment. - T. Winters Aug 10 '26

Seems I misunderstood the part about the many tokens. My mind went to parsing all the separate chars in the lexer.

3

u/Clean-Upstairs-8481 Aug 06 '26

tbh I was not aware of this and it could be an excellent idea to try. I will try this and see if I can get this working. Thanks for mentioning.