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

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jul 30 06:04:56 PDT 2016


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?
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"));
}

Ali



More information about the Digitalmars-d-learn mailing list