Language: CPP
Data
Cereal was developed by USCiLab to provide a modern, easy-to-use, and type-safe serialization library for C++. It leverages C++11 features like templates and smart pointers, making serialization and deserialization intuitive and flexible for both small and complex data structures.
Cereal is a C++11 library for serialization of data structures. It allows converting C++ objects to JSON, XML, or binary formats, and deserializing them back into objects efficiently and safely.
sudo apt install libcereal-devbrew install cerealDownload from https://uscilab.github.io/cereal/ and include headers in your projectCereal allows serialization of standard C++ data types, STL containers, and custom classes. You can serialize objects to JSON, XML, or binary archives, and deserialize them with minimal boilerplate.
#include <cereal/archives/json.hpp>
#include <fstream>
struct MyData {
int x; float y;
template<class Archive>
void serialize(Archive & ar) {
ar(x, y);
}
};
int main() {
MyData data{42, 3.14f};
std::ofstream os("data.json");
cereal::JSONOutputArchive archive(os);
archive(data);
}Serializes a simple struct `MyData` to a JSON file using Cereal.
#include <cereal/archives/json.hpp>
#include <fstream>
MyData data;
std::ifstream is("data.json");
cereal::JSONInputArchive archive(is);
archive(data);
std::cout << data.x << ", " << data.y << std::endl;Reads the JSON file back into a `MyData` object.
#include <cereal/archives/json.hpp>
#include <vector>
#include <fstream>
int main() {
std::vector<int> numbers{1,2,3,4,5};
std::ofstream os("numbers.json");
cereal::JSONOutputArchive archive(os);
archive(numbers);
}Cereal can directly serialize STL containers like vectors, maps, and sets.
struct Point { int x, y; template<class Archive> void serialize(Archive & ar){ ar(x,y); } };
struct Shape { Point p; int size; template<class Archive> void serialize(Archive & ar){ ar(p, size); } };Cereal supports nested structures, recursively serializing inner objects.
#include <cereal/archives/binary.hpp>
std::ofstream os("data.bin", std::ios::binary);
cereal::BinaryOutputArchive archive(os);
archive(data);Cereal can serialize data in binary format for compact storage and faster I/O.
#include <cereal/archives/xml.hpp>
std::ofstream os("data.xml");
cereal::XMLOutputArchive archive(os);
archive(data);Cereal can serialize objects to XML format, which is human-readable and widely used.
Use template `serialize` functions in your classes for custom serialization.
Prefer binary archives for performance and JSON/XML for readability.
Keep serialization code simple and minimal for maintainability.
Avoid serializing pointers directly unless using smart pointers handled by Cereal.
Ensure backward compatibility by adding default values when extending data structures.