How to copy object of class A to another object of class B?
aldanor via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Jan 28 06:56:41 PST 2015
On Wednesday, 28 January 2015 at 11:30:13 UTC, Marc Schütz wrote:
> On Wednesday, 28 January 2015 at 09:44:29 UTC, zhmt wrote:
>> It is boring coding, I want a solution to copy them
>> automatically:
>> void copyObj(SRC,DEST)(SRC src,DEST dest)
>> {
>> foreach (i, type; typeof(SRC.tupleof)) {
>> auto name = SRC.tupleof[i].stringof;
>> __traits(getMember, dest, name) = __traits(getMember, src,
>> name);
>> writeln(name);
>> }
>> }
>>
>> Unfortunitely, it doesnt work, how to improve it?
>
> Haven't tested it, but the `auto name = ...` part is likely to
> be the problem. By using `auto`, your declaring a runtime
> variable, which you then later try to use with
> `__traits(getMember, ...)`, which expects a value known at
> compile time. Try using `alias name = ...`, or if that fails,
> just repeat the expression `SRC.tupleof[i].stringof` wherever
> `name` occurs (though I'm sure there is a nicer way).
And if the alias doesn't work directly, you can always use a
well-known hack:
alias Alias(T) = T;
alias Alias(alias T) = T;
so then this works:
alias member = Alias!(__traits(getMember, Parent, "child"));
Idk if it's a feature or a bug of how getMember works but I had
to use this numerous times.
More information about the Digitalmars-d-learn
mailing list