Because D currently doesn't support RAII using named parameters like in Python I tried the following.

Say I have an aggregate

class C { int x,y,z,w; }

or similarly

struct C { int x,y,z,w; }

I know define a generic _free_ function

ref T set(string member, T, U)(ref T a, in U value) if (isAggregateType!T && hasMember!(T, member))
{
    mixin(`a.` ~ member ~ ` = value;`);
    return a;
}

which I want to use for flexible initialization of several members at once.

However using this function through UFCS

    auto cx = new C().set!"x"(11);

fails as

algorithm_ex.d(1257,17): Error: template algorithm_ex.set cannot deduce function from argument types !("x")(C, int), candidates are: algorithm_ex.d(1242,7): algorithm_ex.set(string member, T, U)(ref T a, in U value) if (isAggregateType!T && hasMember!(T, member))

Instead I have to use

    auto c = new C(); set!"x"(c, 11);

which is not as elegant.

Why doesn't UCFS work here and is there a solution using DMD git master?

Further Is there a cleverer way to do this without resorting to mixins?

This old post

http://forum.dlang.org/thread/mailman.2966.1301533296.4748.digitalmars-d-le...@puremagic.com

talks about opDispatch() but, to my knowledge, it requires the aggregate to have extra members doing the initialization.

I want this because I've identified in some parts of my code that I have large structures were only a few of the elements are initialized to non-default values.

Reply via email to