Puzzled

Petar Petar
Wed Dec 13 12:25:37 UTC 2023


On Wednesday, 13 December 2023 at 03:37:25 UTC, Don Allen wrote:
> On Tuesday, 12 December 2023 at 19:50:25 UTC, monkyyy wrote:
>> On Tuesday, 12 December 2023 at 19:02:11 UTC, Don Allen wrote:
>>> [..]

Try this, it works since dmd 2.087:

```d
struct Foo {
     int bar;
     double baz;

	void bletch(alias field)(typeof(field) newValue) {
         field = newValue;
	}
}

void main(string[] args) {
     import std.stdio;

     Foo s;
     s.bletch!(Foo.bar)(3);
     s.bletch!(s.baz)(4); // this also works - the same as above
     writeln(s);

     auto setBar = &s.bletch!(Foo.bar);
     auto setBaz = &s.bletch!(Foo.baz);

     pragma (msg, typeof(setBar));
     pragma (msg, typeof(setBaz));
     setBar(18);
     setBaz(19.5);
     writeln(s);
}
```

By making `bletch` a member function of `Foo` it will naturally 
have "an instance of type `Foo`" - the implicit `this` parameter 
that all member functions receive. Afterwards, you can see that 
we can take the address of the member function template instance 
`&s.bletch!(Foo.bar)` which results in a `delegate` (and not a 
function pointer). This allows us to call `bletch` through this 
delegate as it will supply `s` as the context pointer.


More information about the Digitalmars-d mailing list