Tessil / ordered-map

C++ hash map and hash set which preserve the order of insertion
MIT License
517 stars 67 forks source link

Serialize with boost and C++11/14 #29

Closed k-vernooy closed 4 years ago

k-vernooy commented 4 years ago

I'm looking to serialize an ordered-map with boost_serialization.

I have seen the below code for splitting into save and load, and using the serialize/deserialize methods of ordered_map, however being unfamiliar with lambdas I am not sure how to adapt this to work with C++11 or C++14.

template<class Archive, class Key, class T>
void serialize(Archive & ar, tsl::ordered_map<Key, T>& map, const unsigned int version) {
      split_free(ar, map, version); 
}

template<class Archive, class Key, class T>
void save(Archive & ar, const tsl::ordered_map<Key, T>& map, const unsigned int /*version*/) {
     auto serializer = [&ar](const auto& v) { ar & v; };
     map.serialize(serializer);
}

template<class Archive, class Key, class T>
void load(Archive & ar, tsl::ordered_map<Key, T>& map, const unsigned int /*version*/) {
     auto deserializer = [&ar]<typename U>() { U u; ar & u; return u; };
     map = tsl::ordered_map<Key, T>::deserialize(deserializer);
}

How would this be done without using templated parameters in the deserializer lambda?

Tessil commented 4 years ago

Hi,

Instead of:

auto deserializer = [&ar]<typename U>() { U u; ar & u; return u; };

you can use something like:


template<class Archive>
class deserializer {
public:
    deserializer(Archive& ar): m_ar(ar) {
    }

    template<typename T>
    T operator()() {
        T t; 
        m_ar & t; 

        return t;
    }

private:
    Archive& m_ar;
};

Thibaut

k-vernooy commented 4 years ago

Thanks, this worked for me!