Puzzled
Walter Bright
newshound2 at digitalmars.com
Wed Dec 13 07:05:10 UTC 2023
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`.
D has 3 ways of passing arguments:
1. by value
2. by pointer (aka by reference)
3. by symbol (aka by alias)
Passing by symbol is strictly a compile time phenomenon, it cannot be a runtime one.
C++'s method of passing by alias is called a "template template parameter", and
is limited to passing the names of template symbols. D generalized it so any
symbol could be passed that way.
C macros can have arguments, and they are always passed by name, which is
roughly similar to by alias. They are also a compile-time phenomenon, not a
runtime one.
More information about the Digitalmars-d
mailing list