setMemberByName

Given a struct/class object, sets one of its members by its string name to a specified value. Overload that takes a value of the same type as the target member, rather than a string to convert. Integer promotion applies.

It does not currently recurse into other struct/class members.

  1. auto setMemberByName(Thing thing, string memberToSet, string valueToSet)
  2. auto setMemberByName(Thing thing, string memberToSet, Val valueToSet)
    setMemberByName
    (
    Thing
    Val
    )
    (
    ref Thing thing
    ,
    const string memberToSet
    ,)
    if (
    isAggregateType!Thing &&
    isMutable!Thing
    &&
    !is(Val : string)
    )

Parameters

thing Thing

Reference object whose members to set.

memberToSet string

String name of the thing's member to set.

valueToSet Val

Value, of the same type as the target member.

Return Value

Type: auto

true if a member was found and set, false if not.

Throws

SetMemberException if the passed valueToSet was not the same type (or implicitly convertible to) the member to set.

Examples

struct Foo
{
    int i;
    double d;
}

Foo foo;

foo.setMemberByName("i", 42);
foo.setMemberByName("d", 3.14);

assert(foo.i == 42);
assert(foo.d = 3.14);
import std.conv : to;
import std.exception : assertThrown;

struct Foo
{
    string s;
    int i;
    bool b;
    const double d;
}

Foo foo;

bool success;

success = foo.setMemberByName("s", "harbl");
assert(success);
assert((foo.s == "harbl"), foo.s);

success = foo.setMemberByName("i", 42);
assert(success);
assert((foo.i == 42), foo.i.to!string);

success = foo.setMemberByName("b", true);
assert(success);
assert(foo.b);

success = foo.setMemberByName("d", 3.14);
assert(!success);

assertThrown!SetMemberException(foo.setMemberByName("b", 3.14));

Meta