C ++, serialization of different types of instances

xiaoxiao2021-03-06  65

Assume that a graphic programming program is written, all graphics classes have a common parent class Graphics. Serialize () for serialization is provided in the Graphics class. Now uses the graphic editor to create multiple graphics objects (ie, an instance of the subclass of multiple Graphics can be created, which can be connected via a CHAIN ​​OF RESPONSIBILITY) and want to save the graphic to a file. We need to traverse the duties, call the Serialize method of each instance in turn. The problem is generated: How do we read these records? How do we know that the current read data is the instance of the instance of instances? The root caused by this problem is that we cannot save the type information of the class into the file.

One solution is to write a single ID message when deposited in the file; Probably code may be like this: void serialize (ar) {case; switch (id) {case subs_class1: newinstance = new subclass1; break; case subs_class2: newinstance = new subclass2 Break; // ...} newinstance.serialize (ar);}} But this seems not a good way, because every time we add a sub-class, you need to add an ID to it. Moreover, a corresponding entry is added to the Switch ... Case structure in the above code. This is very unreliable when the number of as a child is constantly changing. In fact, you can resolve this issue through type registration. First resolve the ID problem, this can take the Loki library Typelist (see my other article). We can use a data structure to save all subclasses (saving this class) Class AbstractBuilder {}; Template Class Builder: Public AbstractBuilder}; public abstractbuilder {public: t> Class Builder: PUBLIC AbstractBuilder {Public: * Clone () {Return New T;}}; // ... void regsiterclassinfo () {classInfolist.push_back (builder tmp1); classinfolist.push_back (builder tmp2); // ...} Void Serialize (CARCHIVE & AR) {Ar >> ID; for (iter = ClassInfolist.begin (); ore! = ClassInfolist.end (); iter) {if (id == iter-> id) {newinstance = iter -> Clone (); Break;} NEWINSTANCE-> Serialize (ar);

转载请注明原文地址:https://www.9cbs.com/read-110763.html

New Post(0)