tupleof of class instance... but enumerate _all_ the instance variables

Nick Treleaven nick at geany.org
Sat Jun 28 10:41:47 UTC 2025


On Friday, 27 June 2025 at 22:33:25 UTC, Andy Valencia wrote:
> tupleof works for struct and class instances, but explicitly 
> documents that it ignores instance variables from any 
> superclass.
>
> Is there any way to enumerate _all_ the instance variables, not 
> just the ones present in the specific instance's class?
>
> Thanks,
> Andy

This is one way:

```d
import std;

class C
{
     int x, y;
}

class D : C
{
     int a, b;
}

void main()
{
     D d = new D;
     static if (is(D Bases == super))
     {
         static foreach (B; AliasSeq!(D, Bases))
         {
             pragma(msg, B);
             static foreach (field; B.tupleof)
             {{
                 enum s = __traits(identifier, field);
                 pragma(msg, s);
                 // access runtime field
                 __traits(getMember, d, s)++;
             }}
         }
     }
     assert([d.tupleof, (cast(C)d).tupleof] == [1,1,1,1]);
}
```

Pragma output:
```
D
a
b
C
x
y
```


More information about the Digitalmars-d-learn mailing list