64,643
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
#pragma once
// save基本类型 int,double, float,bool...
template <class Stream, class T>
void serialize(Stream& stream, T& x) {
stream.write((const char*)&x, sizeof(T));
}
// load
template <class Stream, class T>
void de_serialize(Stream& stream, T& x) {
stream.read((char*)&x, sizeof(T));
}
// 指针
template <class Stream, class T>
void serialize(Stream& stream, T* x) {
bool is_not_null_ptr = x != 0;
serialize(stream, is_not_null_ptr);
if(x) {// if x != 0
serialize(stream, *x);
}
}
template <class Stream, class T>
void de_serialize(Stream& stream, T*& x) {
bool is_not_null_ptr;
de_serialize(stream, is_not_null_ptr);
if(is_not_null_ptr) {
x = new T;
de_serialize(stream, *x);
}
}
// std::string
template <class Stream>
void serialize(Stream& stream, const std::string& str) {
int len = str.length();
serialize(stream, len);
stream.write(str.c_str(), len);
}
template <class Stream>
void serialize(Stream& stream, std::string& str) {
serialize(stream, (const std::string&)str);
}
// string read
template <class Stream>
void de_serialize(Stream& stream, std::string& str) {
int len;
de_serialize(stream, len);
str.resize(len);
char x;
for(int i=0; i<len; i++) {
de_serialize(stream, x);
str[i] = x;
}
}
// 以上部分就是个简单的序列化库了
struct Student {
string num;
string name;
double score;
Student* next;
Student() : next(0) {} // next置0
Student(const string& num, const string& name, double score)
: num(num), name(name), score(score), next(0)
{}
void debug() {
cout << "name: " << name << ", num: " << num
<< ", score: " << score << endl;
if(next) {
next->debug();
}
}
};
template<typename Stream>
void serialize(Stream& s, Student& stu) {
serialize(s, stu.num); //保存Student的各属性
serialize(s, stu.name);
serialize(s, stu.score);
serialize(s, stu.next);
}
template<typename Stream>
void de_serialize(Stream& s, Student& stu) {
de_serialize(s, stu.num);
de_serialize(s, stu.name);
de_serialize(s, stu.score);
de_serialize(s, stu.next);
}
int main() {
Student s1("111", "s1", 100);
Student s2("222", "s2", 60);
s2.next = &s1; // s2包含s1
ofstream ofs("save.txt", ios::binary);
serialize(ofs, s2);
ofs.close();
Student s3;
ifstream ifs("save.txt", ios::binary);
de_serialize(ifs, s3);
s3.debug();//就是上面s2的内容
}