Puzzled

Don Allen donaldcallen at gmail.com
Wed Dec 13 15:55:37 UTC 2023


On Wednesday, 13 December 2023 at 15:46:12 UTC, Don Allen wrote:
> On Wednesday, 13 December 2023 at 07:05:10 UTC, Walter Bright 
> wrote:
>> On 12/12/2023 7:37 PM, Don Allen wrote:
>>> ````
>>> import std.stdio;
>>> 
>>> struct Foo {
>>>      int bar;
>>>      int baz;
>>> }
>>> 
>>> void bletch(alias field)(Foo s, int n) {
>>>      field = n;
>>>      writeln("%d", field);
>>> }
>>> 
>>> int main(string[] args)
>>> {
>>>      Foo s;
>>>      bletch!(s.bar)(s, 5);
>>>      bletch!(s.baz)(s, 6);
>>>      return 0;
>>> }
>>> 
>>> ````
>>> 
>>> Same complaints from the compiler:
>>> ````
>>> [nix-shell:~/Software/d_tests]$ dmd test.d
>>> test.d(16): Error: calling non-static function `bletch` 
>>> requires an instance of type `Foo`
>>> test.d(17): Error: calling non-static function `bletch` 
>>> requires an instance of type `Foo`
>>> (dmd-2.106.0)
>>> ````
>>
>> The trouble here is that `s` is a local variable of `main`. 
>> The `bletch!(s.bar)` is passing `s` not by reference, and not 
>> by value, but by symbol. Inside the body of `bletch`, there is 
>> no way that it can get at the runtime value of the symbol 
>> `main.s`. Hence, the complaint that `bletch` requires a way to 
>> get at the instance of `main.s`.
>
> Note that in the message to which you are replying, I sent two 
> attempts to resolve this. In the first, having seen the 
> compilation errors I got, I came to the same conclusion you 
> describe above. In the second, I added a 'Foo s' parameter and 
> passed main.s to it in the two calls to bletch, which I thought 
> would fix this problem, since now there is an s of type Foo 
> defined in the scope of the field references. To my surprise, 
> it didn't.

I'm going to add a guess here: the field references passed by 
alias to bletch are to main.s.bar and main.s.baz, so passing 's' 
to bletch at runtime doesn't help, since the field references are 
not to bletch.s.bar, etc.


More information about the Digitalmars-d mailing list