How do you serialize an object in C++?

前端 未结 4 1184
天涯浪人
天涯浪人 2020-11-22 08:04

I have a small hierarchy of objects that I need to serialize and transmit via a socket connection. I need to both serialize the object, then deserialize it based on what ty

4条回答
  •  无人共我
    2020-11-22 08:47

    By way of learning I wrote a simple C++11 serializer. I had tried various of the other more heavyweight offerings, but wanted something that I could actually understand when it went wrong or failed to compile with the latest g++ (which happened for me with Cereal; a really nice library but complex and I could not grok the errors the compiler threw up on upgrade.) Anyway, it's header only and handles POD types, containers, maps etc... No versioning and it will only load files from the same arch it was saved in.

    https://github.com/goblinhack/simple-c-plus-plus-serializer

    Example usage:

    #include "c_plus_plus_serializer.h"
    
    static void serialize (std::ofstream out)
    {
        char a = 42;
        unsigned short b = 65535;
        int c = 123456;
        float d = std::numeric_limits::max();
        double e = std::numeric_limits::max();
        std::string f("hello");
    
        out << bits(a) << bits(b) << bits(c) << bits(d);
        out << bits(e) << bits(f);
    }
    
    static void deserialize (std::ifstream in)
    {
        char a;
        unsigned short b;
        int c;
        float d;
        double e;
        std::string f;
    
        in >> bits(a) >> bits(b) >> bits(c) >> bits(d);
        in >> bits(e) >> bits(f);
    }
    

提交回复
热议问题