Array of class intances

bearophile bearophileHUGS at lycos.com
Tue Apr 8 11:44:05 PDT 2008


BCS:
> C[] copyinst = inst.dup;
> foreach(inout i; inst) i = i.dup;

I suggest you to use ref instead of inout, I presume inout keyword will be removed.



lutger:
T[] dup(T)(T[] a)
{
    static if (is(typeof(T.dup)))
    {
        T[] result;
        result.length = a.length;
        foreach(i, val; a)
            result[i] = val.dup;
        return result;
    }
    else
        return a.dup;
}

Nice.

Something like this (untested, it may need debugging!) may be useful for nested arrays (IsArray is true for dynamic or static arrays and false in every other situation):

template DeconstArrType(T) {
    // similar to std.bind.DynamicArrayType
    static if (IsArray!(T))
        alias typeof(T[0])[] DeconstArrType;
    else
        alias T DeconstArrType;
}

DeconstArrType!(TySub)[] deepDup(TySub)(TySub[] seq) {
    static if (is(typeof(TySub.dup))) {
        auto result = new DeconstArrType!(TySub)[seq.length];
        foreach (i, sub; seq)
            result[i] = deepDup(sub);
        return result;
    } else {
        return seq.dup;
    }
}

A generic deepcopy() function that works with everything (that needs the support of a special method in Object class too) may be useful.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list