On Wednesday, 20 April 2016 at 19:58:15 UTC, Tofu Ninja wrote:
To implement a copy/paste/duplicate functionality in a game editor. I have an entity-component system, to duplicate an entity, all it's components need to be duplicated. I have many many components, I don't want to rely on manually writing copy methods for each, it is too error prone. There are only a very few that need special copies, almost all can get by with a simple shallow copy. I would like a generic way to do that shallow copy.

How are you handling loading and saving of your components? Can't you use the same mechanism, without going through the storage format?

Anyway, to answer your question, perhaps something like this: (untested, it probably needs some minor modifications to compile)

T shallowCopy(T)(T source)
{
        assert(source.classinfo == T.typeinfo);
        auto rv = new T;
        shallowCopy(source, rv);
        return rv;
}

void shallowCopy(T)(T source, T target)
{
        foreach(i; 0 .. T.tupleof.length)
        {
                target.tupleof[i] = source.tupleof[i];
        }
        
        import std.traits : BaseClassesTuple;
        alias baseClasses = BaseClassesTuple!T;
        
        static if(baseClasses.length > 0)
        {
                shallowCopy!(baseClasses[0])(source, target);
        }
}



How does D not have shallow copy? Seems like a very basic functionality...

Generally speaking copying class instances is a very bad idea. That's one of the things structs are for.

Reply via email to