Is there a c++ concept
defined for destinguishing serializable types vs. non-serializable types (using cereal
)?
Based on my undrestanding of serilization, there are 3 ways for allowing a type to be serialized:
- It is trivially serialized (using
cereal
provided functionalities, such asint
,std::string
,std::vector<int>
, etc.) - By providing a
serialize
member function. - By providing a a combination of
save
andload
member functions.
I could figure out the following to address categories 2 and 3. But I am unable to write something for detecting “trivially serializable” types (i.e. category 1).
template <typename T>
concept Serialize_Binary = requires(T a) {
{ a.serialize(std::declval<cereal::BinaryOutputArchive&>()) };
};
template <typename T>
concept Save_Binary = requires(T a) {
{ a.save(std::declval<cereal::BinaryOutputArchive&>()) };
};
template <typename T>
concept Load_Binary = requires(T a) {
{ a.load(std::declval<cereal::BinaryOutputArchive&>()) };
};
template <typename T>
concept Serializable =
Serialize_Binary<T> || (Save_Binary<T> && Load_Binary<T>);
Therefore, as expected, the following assertion fails:
static_assert(Serializable<std::vector<int>>,"vector<int> is not serializable");
What I tried in godbolt: https://godbolt.org/z/n4cxj6s5T
Some previous questions that I studied:
Using Cereal to serialize templated polymorphic types in a library
Cereal Add Serialize to Existing Library Class
Cereal std::vector serialization
Saber Gholami is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.