eyalz800 / zpp_bits

A lightweight C++20 serialization and RPC library
MIT License
752 stars 59 forks source link

Need to pass objects as const when using specialized serialization functions #157

Open sjulti opened 7 months ago

sjulti commented 7 months ago

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.

eyalz800 commented 7 months ago

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.