object.factory with template classes for serializing subclasses automatically

timotheecour thelastmammoth at gmail.com
Mon Sep 10 20:19:08 PDT 2012


> I don't understand how Object.factory could help with 
> serializing. But what would help is if we did get proper 
> runtime reflection.

All that'd be needed would be to have Object.factory working with 
templates, here's how:

----
unittest{
     class A{}
     class B{int x;}
     A a=new B;
     auto c=serialize(a);//will serialize field "x", no need to 
register!B
}

auto serialize(T)(T a){
     auto 
c=cast(SerializerBase)Object.factory("Serializer!("~typeid(a).to!string~").Serializer");
     return c.serialize(a);
}

class SerializerBase{//could also be an interface
     auto serialize(Object a){}
}

class Serializer(T):SerializerBase{
     auto serialize(Object a){
         auto b=cast(T)a;
         foreach (name; __traits(allMembers, T)) {
             //now we have access to fields of most derived type;
             //we can get the fields from base class as well.
         }
     }
}
----
I've left out details to focus on the key part. Deserialization 
is very similar.

So the question is: is that technically impossible or not to 
enhance Object.factory in such ways?




More information about the Digitalmars-d-learn mailing list