每当我发现自己需要在C++程序中序列化对象时,我就会回到这种模式:
class Serializable {
public:
static Serializable *deserialize(istream &is) {
int id;
is >> id;
switch(id) {
case EXAMPLE_ID:
return new ExampleClass(is);
//...
}
}
void serialize(ostream &os) {
os << getClassID();
serializeMe(os);
}
protected:
int getClassID()=0;
void serializeMe(ostream &os)=0;
};
Run Code Online (Sandbox Code Playgroud)
以上在实践中效果很好.但是,我听说这种类ID转换是邪恶的,反模式; 什么是在C++中处理序列化的标准OO方式?