Serialization/deserialization of templated class

Eugene Wissner via Digitalmars-d digitalmars-d at puremagic.com
Tue Jun 27 22:01:17 PDT 2017


On Wednesday, 28 June 2017 at 04:41:25 UTC, Dmitry Solomennikov 
wrote:
> Hi, guys!
>
> I have templated classes like this:
>
> class Some(T1) {
>   T1 value;
>   this(T1 _value){
>     value = _value;
>   }
> }
> class Pair(T1, T2) {
>   T1 first;
>   T2 second;
>   this(T1 _first, T2 _second){
>     first = _first;
>     second = _second;
>   }
> }
>
> and a lot of serialised data, which I have to read and 
> instantiate into given classes.
> Serialized data looks like this: 'Some(Pair("df", 5.0))' or 
> 'Pair(Some(true), 11)', i.e. order of structs, its types and 
> inclusion order are unknown at compile time.
>
> I know there are several serialisation libraries, but I found 
> they work only with non-templated classes, like:
>
> class Foo {
>   int a;
> }
>
> I can read input data and parse it, but have no idea how to 
> construct object of templated class in this situation. Please 
> give a hint.

Templates are a compile time feature. You won't be able to 
initialize the classes if you don't know the type at compile time.

You can use some data structure like Variant that can save values 
of different types.
You could use union for data storage in you class and list all 
possible types as union members.
Probably if you have serialized data, you convert strings to 
other types, so it may be possible to perfom if-checks:
if (myDataIsStringAndDouble(data))
{
   auto var = new Some!(Pair!(string, double))(new Pair!(string, 
double)("df", 5.0));
}
else if (myDataIsStringAndInt(data))
{
   auto var = new Some!(Pair!(string, int))(new Pair!(string, 
int)("df", 5));
}


More information about the Digitalmars-d mailing list