getml / reflect-cpp

A C++20 library for fast serialization, deserialization and validation using reflection. Supports JSON, BSON, CBOR, flexbuffers, msgpack, TOML, XML, YAML / msgpack.org[C++20]
https://getml.github.io/reflect-cpp/
MIT License
783 stars 63 forks source link

Concepts to test for serializability #89

Open hlewin opened 2 months ago

hlewin commented 2 months ago

Hello!

Would it be possible to define concepts that check if a type can be serialized (or reflected)? I know there are static assertions in place already, but I would really like to have a way to do something like

static_assert( is_serializable<MyType> )
liuzicheng1987 commented 2 months ago

@hlewin , there are currently no such static assertions.

I think it's certainly doable, but it might be slightly more tricky than you think. What you would want to do is to write a concept that checks whether parsing::Parser<R, W, MyType>::write(...) compiles. (And if you want to support is_deserializable<MyType> as well you could check whether parsing::Parser<R, W, MyType>::read(...) compiles.)

I am assuming that you want to do this independently of any particular serialization format. So that means you have to write your own "mock reader" and "mock writer" for this concept.

The concepts for the reader and writer are laid out in here:

https://github.com/getml/reflect-cpp/blob/main/include/rfl/parsing/IsReader.hpp

https://github.com/getml/reflect-cpp/blob/main/include/rfl/parsing/IsWriter.hpp

A PR is welcome.

liuzicheng1987 commented 2 months ago

@hlewin , in order to conform to C++ standards, I would suggest to add a _v as a suffix:

static_assert( is_serializable_v<MyType> )
static_assert( is_deserializable_v<MyType> )