How do you test whether a variable is static or not?

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jul 30 06:29:55 PDT 2016


On Saturday, July 30, 2016 06:04:56 Ali Çehreli via Digitalmars-d-learn wrote:
> On 07/30/2016 05:47 AM, Jonathan M Davis via Digitalmars-d-learn wrote:
>  > I'm writing some serialization code where I need to skip static
>
> variables.
>
>  > So, I have a symbol from a struct, and I'd like to test whether it's
>
> static
>
>  > or not.
>
> static variables don't have the .offsetof property:
>
> struct S {
>      int a;
>      static int b;
>
> // Bonus question: should field be alias or string?

That depends on what you're doing. __traits(allMembers, ...) gives you a
list of strings, so it may make more sense in the general case to use
string, but in order to actually do much of anything useful, you have to
convert them all to symbols, which is what I've done in my code and why I
was using an alias.

> template isStaticVar(T, alias field)
> {
>      enum isStaticVar = !__traits(compiles, mixin("T." ~ field ~
> ".offsetof"));
> }
>
> void main() {
>      static assert (!isStaticVar!(S, "a"));
>      static assert (isStaticVar!(S, "b"));
> }

Thanks!

- Jonathan M Davis




More information about the Digitalmars-d-learn mailing list