简单c++序列化
看了几个序列化框架,都有这个那个瑕疵
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());
});
});
}
补充:软件开发 , C++ ,