Obtaining an address given a (run time) variable name
Steven Schveighoffer
schveiguy at gmail.com
Fri Jan 24 03:44:25 UTC 2025
On Monday, 20 January 2025 at 19:03:09 UTC, DLearner wrote:
> // In the code below, what fn needs to go in the commented-out
> line,
> // to make the program print 7, 11 rather than 7, 7?
>
You can't I don't think get a list of local variables at this
point, but you can get a list of struct member names.
This is the best I could do:
```d
T* fn(T, Struct)(ref Struct s, string name) {
import std.traits;
switch(name)
{
static foreach(n; FieldNameTuple!Struct) {
case n:
static if(is(T == typeof(__traits(getMember, s, n))))
return &__traits(getMember, s, n);
else assert(0, "field " ~ n ~ " is not of type "
~ T.stringof);
}
default:
assert(0, "field " ~ name ~ " does not exist on type " ~
Struct.stringof);
}
}
void main()
{
static struct S {
int IntVar1 = 5;
int IntVar2 = 7;
int IntVar3 = 11;
}
S s;
auto name = "IntVar3";
auto ptr = s.fn!int(name);
import std.stdio;
writeln(*ptr);
}
```
-Steve
More information about the Digitalmars-d-learn
mailing list