Home >Backend Development >C++ >How to Serialize and Deserialize Classes with Custom Data Type Members in C ?
Serialization of Classes with Custom Data Type Members in C
Problem:
How do you efficiently serialize and deserialize a class containing multiple members of custom data types?
Answer:
To efficiently serialize and deserialize a class containing custom data types, consider the following:
Suggested Interface:
<code class="cpp">std::vector<uint8_t> serialize(Mango const& Man); Mango deserialize(std::span<uint8_t const>> data);</code>
Implementations:
<code class="cpp">std::vector<uint8_t> serialize(Mango const& Man) { std::vector<uint8_t> bytes; do_generate(back_inserter(bytes), Man); return bytes; } Mango deserialize(std::span<uint8_t const> data) { Mango result; auto f = begin(data), l = end(data); if (!do_parse(f, l, result)) throw std::runtime_error("deserialize"); return result; } 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>
Custom Data Types Parsers and Generators:
These handle the serialization/deserialization of your custom data types (see answer for detailed examples).
Portability:
Additional Notes:
The above is the detailed content of How to Serialize and Deserialize Classes with Custom Data Type Members in C ?. For more information, please follow other related articles on the PHP Chinese website!