Is 'alias this' too buggy/limited to be usable?
Dennis
dkorpel at gmail.com
Thu Jan 4 19:14:21 UTC 2018
On Thursday, 4 January 2018 at 18:18:29 UTC, jmh530 wrote:
> As a workaround, you can roll out your own versions of those
> functions, just cast Number to double and then pass it to the
> std.math functions (locally imported). You may also want to
> cast back to Number, or something.
Thanks, but the whole idea of using alias this is to prevent
having to write special extra code. Take for example:
```
import std.math: isNaN;
double parseDouble(string s) {
...
}
unittest {
assert(parseDouble("123") == 123);
assert(parseDouble("NaN").isNaN);
}
```
Now what do you return when the string is malformed? You decide
to change it to:
```
import std.typecons: Nullable;
Nullable!double parseDouble(string s) {
```
Now Nullable has a `get` method and `alias get this`, so this
line still compiles:
assert(parseDouble("123") == 123);
But this line gives an error: it can't instantiate the templated
isNaN on type Nullable!double.
assert(parseDouble("NaN").isNaN);
The best way to fix it is to call get explicitly:
assert(parseDouble("NaN").get.isNaN);
I don't like this 'it mostly still works, but sometimes it
breaks' property when you change 'double' to 'Nullable!double'
which is supposed to extend it. My current solution is to just
enforce you call .get all the time: the workaround is "don't use
alias this"!
More information about the Digitalmars-d
mailing list