Trying to create a serialization macro

Hi,
I am trying to come up with a simple & generic way to serialize my structs. I would like something like a simple macro that i can just place in a struct and pass it the order in which it should serialize the member variables in and it should then automatically implement the stream operators with code that serializes the member variables in the specified order. Also i would like to be able to specify whether the variables should be serialized in little-endian or big-endian format, and on top of this i would like to be able to specify a "custom encoding / decoding procedure" for non-trivial (not sure if thats the correct term to use here) types like user defined classes.

Something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#define SERIALIZABLE(...)                                          \
  void operator>>(std::ostream&& stream)                           \
  {                                                                \
    //insert template metaprogramming magic here                   \  
  }                                                                

struct ExampleStruct
{
  uint32_t foo;
  uint64_t bar;
  CustomLinkedListClass baz;

  SERIALIZABLE( {foo, BigEndian}, {bar, LittleEndian}, {baz, CustomLinkedListEncodingProc} )
};


ExampleStuct example;
example >> std::ofstream{"serialized_struct.dat"};


But my problem is that i'm not very good at template metaprogramming and so i am not entirely sure how to archive this. Can someone help me come up with a way to implement this or does anyone know a better way i could use to serialize my structs?
Last edited on
Have you considered using a code generation tool like Google's protobuf?

https://developers.google.com/protocol-buffers
https://capnproto.org/
https://avro.apache.org/
Topic archived. No new replies allowed.