zpp_bits
zpp_bits copied to clipboard
Need to pass objects as const when using specialized serialization functions
I am serializing std::chrono::time_point
and use the serialize
for that purpose:
struct object {
std::chrono::time_point<std::chrono::system_clock> tp;
constexpr static auto serialize(auto& archive, auto& self) {
std::size_t count = 0;
auto res = archive(self.name, count, self.size);
self.tp = // convert count to time_point
return res;
}
constexpr static auto serialize(auto& archive, const auto& self) {
std::size_t count = self.last_modified.time_since_epoch().count();
return archive(self.name, count, self.size);
}
};
I figured that for writing data, I need to provide overloads for const
objects. However, when calling from a function with a non-const object, it will instead call the de-serialization overload:
object obj;
std::vector<char> bytes;
zpp::bits::out{bytes, zpp::bits::size4b{}}(obj).or_throw(); // this will call the non-const variant, effectively de-serializing the object
As a work-around, I can use std::as_const(obj)
when passing the object to ZPP_bits. It would be nice to receive an error here instead.
Interesting, I will look into that. In the meantime I recommend to try and add a requires clause for each function for archive kind, or go for one function with if constexpr, I believe I had an example in the readme for it.