"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Serialize and Deserialize a C++ Class with Custom Data Types?

How to Serialize and Deserialize a C++ Class with Custom Data Types?

Published on 2024-11-11
Browse:538

How to Serialize and Deserialize a C   Class with Custom Data Types?

How to do serialization of Class having members of custom data types in C ?

Problem

The goal is to serialize and deserialize a C class Mango that contains members of custom data types.

Implementation

The suggested implementation includes the following functions:

std::vector serialize(Mango const& Man);
Mango                deserialize(std::span data);

void serialize_to_stream(std::ostream& os, Mango const& Man);
void deserialize(std::istream& is, Mango& Man);

Customizations for Data Types

Customizations are required for all relevant types (including ValType, FuntionMango, MangoType, and Mango):

// Define `do_generate` and `do_parse` functions
// for custom data types.

Example Implementation

void serialize_to_stream(std::ostream& os, Mango const& Man) {
    do_generate(std::ostreambuf_iterator(os), Man);
}

void deserialize(std::istream& is, Mango& Man) {
    Man = {}; // clear it!
    std::istreambuf_iterator f(is), l{};
    if (!do_parse(f, l, Man))
        throw std::runtime_error("deserialize");
}

Portability Considerations

  • Endianness may need to be normalized, which can be done manually or using a library like Boost Endian (header-only).

Additional Notes

  • This approach allows data to be efficiently stored and transferred between different processes or systems.

Live Example:

https://coliru.stacked-crooked.com/a/288829ec964a3ca9

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3