On 2013-11-13 10:27, Andrei Alexandrescu wrote:

With Object.factory that's taken care of already.

No, you need to register the subclasses as well. The static type information is lost for the subclasses.

Again there is a confusion here. The idea was to create an object with
the dynamic type Foo if the class name was "Foo" and an object with the
dynamic type Bar if the class name was "Bar". You are glossing over the
gist of it all with a function call. Are you sure we are talking about
the same thing?

Here is an excerpt of my serialization library, with the relevant code for this discussion:

void function (in Object) [ClassInfo] registeredTypes;

void register (T : Object) ()
{
    registeredTypes[T.classinfo] = &downcastSerialize!(T)
}

void downcastDeserialize (U : Object) (in Object value)
{
    alias Unqual!(U) T;
    auto casted = cast(T) value;

    assert(casted);
    assert(casted.classinfo is T.classinfo);

    deserializeHelper(casted);
}

void deserializeHelper (T) (T value) { ... }

bool isBaseClass (T) (T value)
{
    return value.classinfo !is T.classinfo;
}

T deserialize (T) (string name)
{
    T t;

    if (auto classInfo = ClassInfo.find(name))
    {
         auto value = cast(T) _d_alloc(classInfo);

        if (isBaseClass(value))
        {
            if (auto deserializer = value.classinfo in registeredTypes)
                (*serializer)(value);

            else
                throw new Exception("Unregistered subclass");
        }

        else
            deserializeHelper(value);

        return value;
    }

    else
    {
        throw new Exception("The class " ~ name ~ " couldn't be found");
        return null;
    }
}

For the full code see: https://github.com/jacob-carlborg/orange/blob/master/orange/serialization/Serializer.d

--
/Jacob Carlborg

Reply via email to