Last active
April 9, 2023 23:27
-
-
Save csullivan/c1085c4ef69905709405d58c1a9b9598 to your computer and use it in GitHub Desktop.
polymorphic data serialization example with cereal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
😄
Quite glad it helped!