看了幾個序列化框架,都有這個那個瑕疵
1. boost 太大,不容易學
2. eternity 不支持非侵入式,必須在類裡加序列化方法。並且不支持 map<int, vector<my_class>> 之類嵌套
3. s11n 太復雜,不支持二進制存儲,導致文件比較大
所以嘗試自己搞了下,目前做到以下功能
1. 非侵入式
2. 支持pod原生類型,如 int, double, 指針
3. 支持stl容器
4. 二進制存儲
例子:
[cpp]
#include <windows.h>
#include <iostream>
#include <fstream>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
#include "serialization.h"
#include "stl/vector.h"
#include "stl/map.h"
#include "stl/string.h"
struct packet {
int x;
string name;
};
typedef map<int, vector<packet>> vmap;
vmap m;
template <class Stream>
void serialize(Stream& stream, packet& p) {
serialize(stream, p.x);
serialize(stream, p.name);
}
template <class Stream>
void de_serialize(Stream& stream, packet& p) {
de_serialize(stream, p.x);
de_serialize(stream, p.name);
}
vector<packet*> vv;
int main() {
packet* p1 = new packet;
p1->x = 10; p1->name = "p1";
packet* p2 = new packet;
p2->x = 20; p2->name = "p2";
vv.push_back(p1);
vv.push_back(p2);
ofstream ofss;
ofss.open("pppppppppp.txt", ios::binary);
serialize(cout, vv);
ofss.close();
vv.clear();
ifstream ifss;
ifss.open("pppppppppp.txt", ios::binary);
de_serialize(ifss, vv);
ifss.close();
printf("vv.size=%d\n", vv.size());
for_each(vv.begin(), vv.end(), [](packet* pp) {
printf("x: %d, name:%s\n", pp->x, pp->name.c_str());
});
printf("================\n");
packet p;
p.x = 3; p.name = "name1";
m[1].push_back(p);
p.x = 4; p.name = "name2";
m[2].push_back(p);
ofstream ofs;
ofs.open("zzzzzzzzzzzzzzzzzzzzzzz.txt", ios::binary);
serialize(ofs, m);
ofs.close();
// ZeroMemory(&p, sizeof(p));
m.clear();
ifstream ifs;
ifs.open("zzzzzzzzzzzzzzzzzzzzzzz.txt", ios::binary);
de_serialize(ifs, m);
ifs.close();
printf("m.size = %d\n", m.size());
for_each(m.begin(), m.end(), [](pair<int, vector<packet>> p) {
printf("m[%d].size=%d\n", p.first, p.second.size());
for_each(p.second.begin(), p.second.end(), [](packet p) {
printf("x = %d, name=%s\n", p.x, p.name.c_str());
});
});
}