Dealing with unordered_map of abstract classes and serialization

  abstract, boost, c++, oop, serialization

Say I have the following structs:

struct Base {
    virtual int get_x() = 0;
}

struct A : Base {
    int get_x() {
         // ...
         return 0;
    }
}

struct B : Base {
    int get_x() {
         // ...
         return 1;
    }
}

I also have serialization methods for these classes:

BOOST_SERIALIZATION_SPLIT_FREE(A);
namespace boost {
    namespace serialization {
        template<class Archive>
        void save(Archive & ar, const A & a,
                        const unsigned int version) {
            // ...
        }
        template<class Archive>
        void load(Archive & ar, A & a,
                        const unsigned int version) {
            // ...
        }
    }
}

// same for B

In my code, I’m making an unordered_map<int, A>. I have functions to save and load this map:

inline void save_map(string filename, unordered_map<int, A>& a_dict) {
    ofstream filestream(filename);
    boost::archive::binary_oarchive archive(filestream,
                                            boost::archive::no_codecvt);

    archive << a_dict;
}

inline void load_map(string filename, unordered_map<int, A>* a_dict) {
    ifstream filestream(filename);
    boost::archive::binary_iarchive archive(filestream,
                                            boost::archive::no_codecvt);

    archive >> *a_dict;
}

I now want to generalize my map definition and these functions in an elegant way so my code is agnostic to whether my objects are A or B. Obviously I run into object slicing issues if I, for example, just start using unordered_map<int, Base>, but I’ve gotten a bit lost in the weeds of pointers at this point and haven’t been able to figure out the solution.

Source: Windows Questions C++

LEAVE A COMMENT