| October 02, 2018Use std.traits.getSymbolsByUDA to access members of instance. | ||||
|---|---|---|---|---|
| 
 | ||||
| I can use `std.traits.getSymbolsByUDA` to get all the members of a class that have a particular UDA `getSymbolsByUDA(ValueType, UDA)`. But how do I get the values with it? Is there a more convenient way than `__traits(getMember, value, getSymbolsByUDA(ValueType, UDA)[0].stringof)`? | ||||
| October 03, 2018Re: Use std.traits.getSymbolsByUDA to access members of instance. | ||||
|---|---|---|---|---|
| 
 | ||||
| Posted in reply to Jonathan | On Tuesday, 2 October 2018 at 03:30:50 UTC, Jonathan wrote:
> I can use `std.traits.getSymbolsByUDA` to get all the members of a class that have a particular UDA `getSymbolsByUDA(ValueType, UDA)`.
>
> But how do I get the values with it?
>
> Is there a more convenient way than `__traits(getMember, value, getSymbolsByUDA(ValueType, UDA)[0].stringof)`?
You can use .tupleof and hasUDA instead:
import std.traits;
import std.stdio;
enum uda1;
enum uda2;
class S {
    @uda1 int a = 1;
    @uda2 int b = 2;
    @uda1 int c = 3;
    @uda2 int d = 4;
}
void main() {
    auto s = new S;
    static foreach (i, _; S.tupleof) {
        static if (hasUDA!(_, uda1))
            writefln("uda1 (%s): %s", __traits(identifier, _), s.tupleof[i]);
    }
    static foreach (i, _; S.tupleof) {
        static if (hasUDA!(_, uda2))
            writefln("uda2 (%s): %s", __traits(identifier, _), s.tupleof[i]);
    }
}
 | |||
Copyright © 1999-2021 by the D Language Foundation
  Permalink
Permalink Reply
Reply