On Thursday, 1 November 2018 at 16:14:45 UTC, Neia Neutuladh wrote:
The spec says that a user-defined attribute must be an expression, but DMD accepts a wide range of things as UDAs:

  struct Foo { string name = "unknown"; }
  @Foo int bar;

`bar` has the *type* Foo as an attribute. It's not an *instance* of Foo. So if I try to look at the UDAs:

  static foreach (uda; __traits(getAttributes, bar))
  {
    static if (is(typeof(uda) == Foo))
    {
      pragma(msg, "bar is @Foo");
    }
  }

That just doesn't work; typeof(Foo) isn't anything, so is(typeof(Foo) == Foo) is false.

I can change my code to read `static if (is(uda == Foo))`. But that obviously fails:

  @Foo("customName") int bar2;

What do you do to handle this?

Check if an UDA is a type?.. As in, not just `is(uda == Foo)`, but simply `is(uda)`:

```
struct Foo { string name = "unknown"; }
@Foo @string @Foo("hello") int bar;

static foreach (uda; __traits(getAttributes, bar)) {
    static if (is(uda)) {
        // if `uda` is a type...
        static if (is(uda == Foo)) {
            pragma(msg, "bar is @Foo!!!");
        } else {
            pragma(msg, "bar is "~uda.stringof);
        }
    } else {
        // if `uda` is not a type...
        pragma(msg, "bar is "~uda.stringof);
    }
}
```

Reply via email to