atilaneves / cerealed

Powerful binary serialisation library for D
BSD 3-Clause "New" or "Revised" License
92 stars 3 forks source link

Deserialize through base class reference? #18

Open helikopterodaktyl opened 6 years ago

helikopterodaktyl commented 6 years ago

I see that there is a sample for serializing through base class reference:

Cereal.registerChildClass!ChildClass;
BaseClass obj = ChildClass(3, 7);
assert(obj.cerealise == [0, 0, 0, 3, 0, 0, 0, 7]);

However, as the assert shows, the derived class name isn't stored anywhere. So when deserializing, you need to know the type anyway. Imagine serializing a BaseClass[]. Some elements of the array are instances of BaseClass, some are instances of ChildClass. Shouldn't in the case of classes an identifier be stored saying what is the real class that is being stored? Something like "assert(obj.cerealise == ["BaseClass", 0, 0, 0, 3, 0, 0, 0, 7]);", so that later on in the code you can do:

Cereal.registerChildClass!ChildClass;
BaseClass obj = datastream.decerealise()

and obj will be actually the ChildClass instance?

atilaneves commented 6 years ago

Good point. I added class serialisation mostly for completeness purposes. I wrote cerealed for networking protocols and I can't see how anyone would want to use classes there. I may even have added the serialisation via the base class due to another issue, I don't remember.

This would quite clearly be a bit of work.