Puzzled

Don Allen donaldcallen at gmail.com
Wed Dec 13 03:37:25 UTC 2023


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:
>> 
>> I'm probably missing something here, perhaps some important 
>> cases where the behavior I'm seeing *does* make sense. I'd be 
>> interested in the comments of those who know D (and perhaps 
>> C++) better than I do.
>
> Your imagining aliases as words rather than references to 
> definitions
>
> As far as I know, aliases are optimized to work with "overload 
> sets"
> ```d
> void foo(int);
> void foo(bool);
>
> template bar(alias A){}
> bar!foo;
> ```
> A is now all foo's, foo's need to exist, and foo mostly 
> pretends to stop knowing where it comes from
>
> do:
>
> ```d
> struct Foo {
>     int bar;
>     int baz;
> }
>
> void bletch(alias field)(int x) {
> 	field = x;
> 	writeln("%d", s.field);
> }
>
> int main(string[] args)
> {
>     Foo s;
>     bletch!(s.bar);
>     bletch!(s.baz);
>     return 0;
> }
> ```

I regard templates as a form of more hygienic macros than simple 
text substitution. To me, they are a form of meta-programming -- 
code writing code. My view may be wrong and if so, I'd like to 
know why. If not, I have not seen an answer that explains why a 
symbol passed to an alias parameter needs a definition in the 
scope of the template instantiation, as opposed to within the 
instantiated template body.

What you have suggested above is a way to make my little example 
work. While less interested in that, I'm not un-interested :-) So 
I played with this a bit.

Taking your approach, cleaned up a bit (the bletch calls need the 
int argument), I tried
````
import std.stdio;

struct Foo {
     int bar;
     int baz;
}

void bletch(alias field)(int n) {
	field = n;
	writeln("%d", field);
}

int main(string[] args)
{
     Foo s;
     bletch!(s.bar)(5);
     bletch!(s.baz)(6);
     return 0;
}
````

This results in
````
[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)
````

Since field is aliased to s.bar or s.baz, I tried this:

````
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)
````





More information about the Digitalmars-d mailing list