Skip to content

Instantly share code, notes, and snippets.

@csullivan
Last active April 9, 2023 23:27
Show Gist options
  • Save csullivan/c1085c4ef69905709405d58c1a9b9598 to your computer and use it in GitHub Desktop.
Save csullivan/c1085c4ef69905709405d58c1a9b9598 to your computer and use it in GitHub Desktop.
polymorphic data serialization example with cereal
#include <iostream>
#include <vector>
#include <memory>
#include <cereal/archives/binary.hpp>
#include <cereal/types/vector.hpp>
#include <cereal/types/string.hpp>
#include <cereal/types/base_class.hpp>
#include <cereal/types/memory.hpp>
#include <cereal/access.hpp>
using namespace std;
class Parent; // Forward declares
class Child; // so my classes are in your order
class Family {
friend class cereal::access;
public:
Family() { ; }
~Family() { ; }
vector<std::shared_ptr<Parent> > m_members;
private:
template <class Archive>
void serialize( Archive & ar )
{ ar( m_members ); }
};
class Parent {
friend class cereal::access;
public:
Parent() : m_name("") { ; }
Parent(string name) : m_name(name) { ; }
~Parent() { ; }
virtual string GetName() { return m_name; }
private:
string m_name;
template <class Archive>
void serialize( Archive & ar )
{ ar( m_name ); }
};
class Child : public Parent {
friend class cereal::access;
public:
Child() : Parent(), m_age(0) { ; }
Child(string name, int id) : Parent(name), m_age(id) { ; }
~Child() { ; }
int m_age;
private:
template <class Archive>
void serialize( Archive & ar )
{ ar( cereal::base_class<Parent>( this ), m_age ); }
};
CEREAL_REGISTER_TYPE(Child)
int main() {
auto timmy = std::make_shared<Child>("Timmy", 4);
Family JohnsonFamily;
JohnsonFamily.m_members.push_back(timmy);
std::stringstream ss;
cereal::BinaryOutputArchive arout(ss);
arout(JohnsonFamily);
cereal::BinaryInputArchive arin(ss);
Family FosterFamily;
arin( FosterFamily );
auto baseptr = FosterFamily.m_members[0];
auto child = dynamic_cast<Child*>(baseptr.get());
if (child != nullptr) {
cout << "Derived type infered from serialized base pointer." << endl;
cout << child->GetName() << " is " << child->m_age << endl;
}
return 0;
}
@AloyASen
Copy link

as of 2020 october this is the only available gist using deserialization .... you saved my day ... thanks @author

@csullivan
Copy link
Author

😄
Quite glad it helped!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment