Struct fields and properties as alias members

Adam D Ruppe destructionator at
Wed Dec 8 17:44:47 UTC 2021

On Wednesday, 8 December 2021 at 17:19:32 UTC, Ben Jones wrote:
> It seems like maybe I'd have to pass s as a runtime parameter 
> to get it to work?

yes, you do. the alias param passes the abstract idea of the 
variable instead of the variable:

> void main(){
>     S s;
>     func!(s.a)();

See, you said `s` here, but the compiler ACTUALLY passes `S.a` - 
the type reference instead of the instance reference.

That's why it complains about missing `this` - the compiler 
dropped it. The `this` is a runtime reference, and the alias 
works on compile time references.

You can pass a runtime reference in addition to the alias and put 
them back together with __traits(child), but be warned, the 
compiler also can get pretty stupid when pass so you need to make 
`func` static since when it sees the alias it assumes it must be 
a member. Weird but easy fix:

import std.stdio;

struct S{
     int a = 1;
     int b = 2;

     @property int c(){ return a; }
     @property int c(int newc) { a = newc; return a;}

// made static, added a ref S to act as `this`
static void func(alias field)(ref S s){
      // now the traits child re-attaches `s` as the this
      // reference to the alias
  	writeln(__traits(child, s, field));
     __traits(child, s, field) = 5;
void main(){
     S s;
     func!(s.a)(s); // passing both ct alias and runtime this


More information about the Digitalmars-d-learn mailing list