Use Boost for Serialization
09 Dec 2016Use boost on MacOS:
1. Install boost:
$ ./b2 install
2. Setup Xcode:
Header Search Paths:
/usr/local/boost
Library Search Paths:
/usr/local/boost/stage/lib
Linked Frameworks an Libraries:
Add dylib in /usr/local/boost/stage/lib
Other Linker Flags:
-lboost_serialization
3. Example serialization:
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/map.hpp>
#include <map>
#include <iostream>
#include <fstream>
struct A {
std::string aString;
bool aBool;
A() {}
A(std::string s, bool b) {
aString = s;
aBool = b;
}
private:
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive &ar, const unsigned int version) {
ar & aString;
ar & aBool;
}
};
struct B {
std::string bString;
std::map<std::string, A> aMap;
B(std::string s) {
bString = s;
aMap = std::map<std::string, A>();
}
void AddA(std::string key, A a) {
aMap[key] = a;
}
private:
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive &ar, const unsigned int version) {
ar & bString;
ar & aMap;
}
};
void save() {
std::ofstream file("archive.bin");
boost::archive::text_oarchive oa(file);
A a = A("This is A struct", true);
B b = B("This is B struct");
b.AddA("A", a);
oa << b;
}
void load() {
std::ifstream file("archive.bin");
boost::archive::text_iarchive ia(file);
B b = B("This is new B struct");
ia >> b;
std::cout << b.bString << std::endl;
std::cout << b.aMap["A"].aString << std::endl;
}
int main() {
save();
load();
}
Use boost on Windows:
1. Install boost:
$ bootstrap
$ .\b2 --build-type=complete address-model=64
2. Setup Visual Studio:
VC++ Directories -> Include Directories:
boost
VC++ Directories -> Library Directories:
boost/stage/lib
C/C++ -> Precompiled Headers:
Not Using Precompiled Headers