hasStaticMember and enums

Petar Petar
Tue Sep 22 11:04:28 UTC 2020

On Monday, 21 September 2020 at 23:33:17 UTC, Steven 
Schveighoffer wrote:
> I was confused today when I was looking to see if a particular 
> field name was a field of a struct and not a static member.
> I thought __traits(hasMember, T, item) && !hasStaticMember!(T, 
> item) would suffice. But then I found that this returns true 
> for enums that are part of the type.
> struct S
> {
>    enum e = "hello";
> }
> static assert(__traits(hasMember, S, "e"));
> static assert(!hasStaticMember!(S, "e"));
> The reason is because hasStaticMember ultimately uses:
> alias sym = Alias!(__traits(getMember, U, member));
> ...
> enum hasStaticMember = __traits(compiles, &sym);
> which of course doesn't compile for an enum.
> But I would actually consider an enum to be a static member. 
> It's a member, but does not consume any part of the instance.
> The docs for hasStaticMember are pretty slim, but it was added 
> here: https://github.com/dlang/phobos/pull/5112
> There is no mention of how this should play with enums. Would 
> it be bad to add a check for enums in this? I was thinking of 
> changing the __traits(compiles) line to:
> __traits(compiles, (auto ref a) { } (sym));
> or something like that.
> Thoughts?

I'd say aggregates have 4 different types of members:
* instance fields and functions
* static fields and functions
* enum fields and functions (though enum functions may become 
regular instance/static functions if https://wiki.dlang.org/DIP27 
is accepted).
* alias-es (a case could be made that from an aggregate user 
point of view, alias members should be indistinguishable from 
normal members, but technically they're different, and this could 
be important for meta code to be able to distinguish. Also there 
are things like certain types of alias sequences that can't be 
neither instance, static or enum members.)

> I'm also not sure why std.meta.Alias is used instead of a 
> normal alias (maybe that used to be an issue? I tried just a 
> straight alias and it works at least in this case).
> -Steve

Before a couple of releases you couldn't alias the result of 
__traits() expressions and mixins (among other limitations), and 
this code predates those language improvements.

More information about the Digitalmars-d mailing list