Generic Property Implementation
Mike Franklin
slavo5150 at yahoo.com
Fri Mar 9 23:34:56 UTC 2018
On Friday, 9 March 2018 at 14:46:04 UTC, Simen Kjærås wrote:
> This is the best I've come up with in the current language:
>
> struct S {
> int n;
> mixin property!("field", "get => this.n", "set => this.n =
> set");
> }
Not bad. Not good, but not bad either.
> Sadly, there are issues:
>
> 1) Wrong return type:
> unittest {
> S s;
> auto a = s.field;
> // Fails - typeof(a) is Property!((get) => this.n, (set) =>
> this.n = set)
> assert(is(typeof(a) == int));
> }
This looks like a related issue:
https://issues.dlang.org/show_bug.cgi?id=16657. That's is a
deal-breaker for me, but I think it could be fixed.
> 2) Noisy syntax:
> If I had my druthers, mixin templates would be mixin'd
> automatically, and eponymous mixin templates would be a thing.
Yes, this would be nice, but I don't think it's a deal-breaker.
> 3) Stringy functions:
> The string literal functions are an eyesore, but would require
> some compiler work to fix. This fails:
>
> struct S {
> int n;
> mixin property!("field", get => this.n, set => this.n =
> set);
> }
>
> The reason is there's no 'this' at the point of instantiation,
> since we're in the context of the type, not a function where
> 'this' makes sense. It seems to me this should be fixable, but
> I have no idea how much work would be required.
Yeah, that's quite unfortunate; writing code in strings stinks.
I actually prefer the DIP for this issue alone.
> 4) 'this' in function bodies
> It should be possible to write "get => this.n" as "get => n".
> There's no ambiguity as to which 'n' I'm referring to. Filed a
> bug:
> https://issues.dlang.org/show_bug.cgi?id=18584
Thanks for filing the issue. I just might be able to fix it;
I'll try.
> Implementation:
> https://gist.github.com/Biotronic/5849af011cbe9c7ea05515011d5995bf
You've done some great work here. I spent about an hour on this
yesterday, and my implementation started to require more and more
mixing strings to get it to work.
If all of the issues you've identified were addressed, you'd end
up with something like this (formatted in a C# way).
struct S {
int n;
property!
(
get =>
{
n
},
set =>
{
n = set
}
) field;
}
That's actually pretty darn good. It makes me wonder if I should
work on fixing those issues or continue with the DIP.
If you don't have any objections I'd like to incorporate this
implementation and your analysis into the DIP.
Thank you again for doing this; you've saved me a awful lot of
time, and have done more than I probably could have.
Mike
More information about the Digitalmars-d-learn
mailing list