Hi all,

I'm implementing a deep-copy method for a tree of templated class instances. As part of this, I need some way to copy each node. I want to avoid code that does things like casting objects into byte arrays and then copying raw bytes; I want all operations to be memory safe things that I can use at compile-time. So I planned to make all of these have default constructors and use Object.factory to at least create the correct instance type at the destination. The classes can implement auxiliary copy methods if they need to copy anything that isn't already handled by their deepCopy method.

But I ran into a problem: Object.factory doesn't seem to be compatible with templated classes.

Here is an example:

import std.stdio;

class Root(T)
{
        T x;
}

class Extended(T) : Root!T
{
        T y;
}

void main()
{
        Root!int foo = new Extended!int();

        auto name = foo.classinfo.name;
        writefln("foo's name is '%s'", name);
        // foo's name is 'main.Extended!int.Extended'

        Object   obj = Object.factory(name);
        writefln("Is obj null? %s", obj is null);

        Root!int bar = cast(Root!int)obj; // Still going to be null.
        writefln("Is bar null? %s", obj is null);

        //bar.x = 3; // crash!
}


I had a look at Object.factory. It seems very simple. Perhaps too simple. I think this might be a dead end. Have I missed something? Can it actually handle templates somehow, but I just don't know how to calculate the correct string to hand it?

If Object.factory is incapable of this, is there some other CTFE-friendly way to copy templated class instances?

If I have to, I can probably make these things register themselves in some list of delegates that can be used to instantiate the correct class. Or something like that. But I am hoping that there is a better way that involves less boilerplate.

Thanks!
- Chad

Reply via email to