How do I set a class member value by its name in a string?
Mengu
mengukagan at gmail.com
Wed Dec 27 21:39:49 UTC 2017
On Wednesday, 27 December 2017 at 20:54:17 UTC, bitwise wrote:
> On Wednesday, 27 December 2017 at 20:04:29 UTC, Marc wrote:
>> I'd like to set the members of a class by its name at runtime,
>> I would do something like this:
>>
>>> __traits(getMember, myClass, name) = value;
>>
>> but since name is only know at runtime, I can't use
>> __traits(). What's a workaround for this?
>
> I think you could write something using a combination of these
> two things:
>
> https://dlang.org/phobos/std_traits.html#FieldNameTuple
> https://dlang.org/phobos/std_traits.html#Fields
>
> or maybe '.tupleof':
>
> https://dlang.org/spec/struct.html#struct_properties
there's also a simple workaround for fields with the same type:
https://run.dlang.io/is/dsFajq
import std.stdio;
struct S {
int x;
int y;
}
auto setValue(ref S s, string field, int value) {
foreach (fieldName; __traits(allMembers, S)) {
if (fieldName == field) {
__traits(getMember, s, fieldName) = value;
break;
}
}
}
void main() {
S s;
s.setValue("x", 5);
s.setValue("y", 25);
writeln(s);
}
you can play with it to make it more generic. you can also create
a mixin template that would generate setters for each field you
would need a setter for and then in the run time you'd just be
able to call them.
More information about the Digitalmars-d-learn
mailing list