How to disable assigning a value to a property?

jfondren julian.fondren at gmail.com
Tue Jul 6 15:24:37 UTC 2021


On Tuesday, 6 July 2021 at 10:06:11 UTC, Jack Applegame wrote:
> How to disable `register.clock = 10;` but allow 
> `register.clock(1) = 10;`?
> I want to get a compilation error on `register.clock = 10;`

Some options:

1. return a temporary struct with an opIndex

```d
import std.stdio;

struct Field {
     void opAssign(int a) {
         writefln("Field.opAssign(%s)", a);
     }
}

struct ClockAssign {
     Field opIndex(int a) {
         writefln("Register.clock(%s)", a);
         return Field();
     }
}

struct Register {
     ClockAssign clock() {
         return ClockAssign();
     }
}

void main() {
     Register register;
     register.clock[1] = 10; // works, good
     //register.clock = 10; // error
}
```

2. https://run.dlang.io/is/bkV64U - keep track of fields and fail 
at runtime if a field was never initialized (because it was 
silently discarded in this case).

3. https://run.dlang.io/is/AJM6Vg - hybrid where ClockAssign has 
an unsafe pointer that the compiler complains about :/


More information about the Digitalmars-d-learn mailing list