Flexible Default Function Parameters via structs with Nullable Fields
Simen Kjærås
simen.kjaras at gmail.com
Tue Apr 30 13:44:00 UTC 2019
On Tuesday, 30 April 2019 at 13:10:54 UTC, Adam D. Ruppe wrote:
> On Tuesday, 30 April 2019 at 08:20:29 UTC, JN wrote:
>> It might be nifty by D standards, but for a person not
>> familiar with D
>
> Or, as someone familiar with D, I wonder why not just use a
> plain struct. D allows you to set initial values for struct
> members plainly.
Yeah, though I can see some use cases for a struct with all
nullable fields and a way to combine with a regular version of
that struct. This could be made a lot easier than in the article:
import std.traits : FieldNameTuple;
import std.typecons : Nullable;
struct Partial(T) if (is(T == struct)) {
static foreach (e; FieldNameTuple!T)
mixin("Nullable!(typeof(__traits(getMember, T, e)))
"~e~";");
}
auto combine(T, PT)(T t, PT pt) if (is(PT == Partial!T)) {
T result;
static foreach (e; FieldNameTuple!T)
__traits(getMember, result, e) = __traits(getMember, pt,
e).get(__traits(getMember, t, e));
return result;
}
struct S {
int x,y;
}
unittest {
S a = S(1,2);
Partial!S b;
b.x = 3;
assert(a.combine(b) == S(3,2));
}
Now, for the abomination that is
callMemberFunctionWithParamsStruct!(t, "f")(combined)... It's
just t.f(combined.tupleof) in a bad disguise, and I really can't
see the benefit.
Lastly, the use of a mixin to define the struct ensures you can't
put methods on the struct, thus drastically reducing usability.
All in all, it's a fun beginner's project, but the quality may
not be good enough that it should be on the blog.
--
Simen
More information about the Digitalmars-d-announce
mailing list