Home > Article > Backend Development > How to Serialize and Deserialize a C Class with Custom Data Types?
The goal is to serialize and deserialize a C class Mango that contains members of custom data types.
The suggested implementation includes the following functions:
<code class="cpp">std::vector<uint8_t> serialize(Mango const& Man); Mango deserialize(std::span<uint8_t const> data); void serialize_to_stream(std::ostream& os, Mango const& Man); void deserialize(std::istream& is, Mango& Man);</code>
Customizations are required for all relevant types (including ValType, FuntionMango, MangoType, and Mango):
<code class="cpp">// Define `do_generate` and `do_parse` functions // for custom data types.</code>
<code class="cpp">void serialize_to_stream(std::ostream& os, Mango const& Man) { do_generate(std::ostreambuf_iterator<char>(os), Man); } void deserialize(std::istream& is, Mango& Man) { Man = {}; // clear it! std::istreambuf_iterator<char> f(is), l{}; if (!do_parse(f, l, Man)) throw std::runtime_error("deserialize"); }</code>
Live Example:
https://coliru.stacked-crooked.com/a/288829ec964a3ca9
The above is the detailed content of How to Serialize and Deserialize a C Class with Custom Data Types?. For more information, please follow other related articles on the PHP Chinese website!