digitalmars.D.learn - static alias this and if/do/while/for
- Jack Applegame (8/21) Oct 22 2020 There is a funny feature (or bug) in the D language:
- Vladimirs Nordholm (3/7) Oct 26 2020 Haha, that's pretty neat!
- Q. Schroll (20/41) Oct 26 2020 It doesn't surprise me that much. What actually did was that
There is a funny feature (or bug) in the D language: static alias this and static operator overloading. For exampleinterface Foo { static { int value; void opAssign(int v) { value = v; } int get() { return value; } alias get this; } }Now we can use type Foo as if it were an lvalue/rvalue:Foo = 5; int a = Foo; int b = Foo + a;I heavily use this feature in my MCU library. But it doesn't work inside conditionals:if(Foo) {} // Error: type Foo is not an expression while(Foo) {} // Error: type Foo is not an expressionEven if we define `static opCast!bool()`. It doesn't help. Should this be fixed?
Oct 22 2020
On Thursday, 22 October 2020 at 21:55:59 UTC, Jack Applegame wrote:Now we can use type Foo as if it were an lvalue/rvalue:Haha, that's pretty neat!Foo = 5; int a = Foo; int b = Foo + a;
Oct 26 2020
On Thursday, 22 October 2020 at 21:55:59 UTC, Jack Applegame wrote:There is a funny feature (or bug) in the D language: static alias this and static operator overloading. For exampleIt doesn't surprise me that much. What actually did was that static opIndex() works. Consider this: struct X { static int opIndex() { return 1; } } alias SliceOf(T) = T[]; enum ValueOf(T) = T[]; static assert( ! is(int[SliceOf!X] == int[ValueOf!X])); But static opIndex and friends can be useful: https://run.dlang.io/is/s15zS0 I'd actually find it awesome if we had opCallAssign and opCallOpAssign; the reason I used opIndex and not opCall is that way, one gets access to the right-hand side and to-assign parameters by reference, so no internal pointer stuff's needed.interface Foo { static { int value; void opAssign(int v) { value = v; } int get() { return value; } alias get this; } }Now we can use type Foo as if it were an lvalue/rvalue:Foo = 5; int a = Foo; int b = Foo + a;I heavily use this feature in my MCU library.But it doesn't work inside conditionals:Only using Foo.opCast!bool works; cast(bool) won't compile.if(Foo) {} // Error: type Foo is not an expression while(Foo) {} // Error: type Foo is not an expressionEven if we define `static opCast!bool()`. It doesn't help.Should this be fixed?The bool stuff should be fixed. The other direction would be a breaking change.
Oct 26 2020