3 ms·
Here's something like that I wrote in C++ in 2017 for JSON using Boost.Fusion + simple function overloading of a single 'from_json' function for handling differ
by nly 2y ago
Here's something like that I wrote in C++ in 2017 for JSON using Boost.Fusion + simple function overloading of a single 'from_json' function for handling different types. It works for nested objects, it's runtime type checked, and all numeric conversions are checked for loss while being forgiving.
https://gist.github.com/nlyan/045fbe075b4e51d83be0cf4513fecd68 https://gist.github.com/nlyan/045fbe075b4e51d83be0cf4513fecd...
The DEFINE_JSON macro is a tiny wrapper around BOOST_FUSION_DEFINE_STRUCT so the whole parsing routine effectively gets unrolled at compile time.
https://www.boost.org/doc/libs/1_87_0/libs/fusion/doc/html/fusion/adapted/define_struct.html https://www.boost.org/doc/libs/1_87_0/libs/fusion/doc/html/f...
The code predates broad availability of std::optional (so uses boost::optional), [[unlikely]] and the existence of Boost.JSON, so if i were using this technique today that's what I'd use, but at the time I used the taocpp JSON library (which is still actively maintained 8 years later)
https://github.com/taocpp/json https://github.com/taocpp/json
Here's an article talking about the technique from a CppCon 2014 talk - "Implementing Wire Protocols with Boost Fusion --Thomas Rodgers"
https://isocpp.org/blog/2015/01/cppcon-2014-implementing-wire-protocols-with-boost-fusion-thomas-rodgers https://isocpp.org/blog/2015/01/cppcon-2014-implementing-wir...
- boricj 2y agoIt's fairly different than the approach inside the CppCon 2014 talk because the data model itself is not actually strongly tied to the underlying types of the data. That lack of strong integration does result in a bit more boiderplate code, but it allows more flexibility. In principle, the data model and the actual data can be quite different as long as you can bridge the two together with the boilderplate code. It's more like projecting a JSON schema over a bunch of various getters and setters and running visitors through them, with some helpers to automatically grok STL-like containers.
- nly 2y agoYeah, an extra layer of type indirection for expressing various implicit encodings is useful for e.g. dates My point overall is that there is tonnes of prior art for compile time reflection libraries in c++ for this kind of thing. Boost has MPL, Fusion and Hana for starters. All of these have visitor patterns and algorithms out of the box. You originally said you hadn't found anything quite like it for unmanaged languages...but people have been doing this for decades at this point. In general I'm no longer a fan of the "encode the schema directly in C++" approach if the data i'm interfacing with actually has a schema.