static if - unexpected results

DLearner bmqazwsx123 at gmail.com
Fri Jun 23 14:22:24 UTC 2023


Hi

Was looking for compile-time detection of a struct variable.
However, the following test code gave the two 'FAILS' shown below.
Comments?
```
void main() {
    import std.stdio : writeln;
    import std.traits;

    string mxnTst(string VarName) {
       return

       `static if (is(typeof(` ~ VarName ~ `) == char)) {` ~
          `writeln("` ~ VarName ~ ` ", " is a char");` ~
       `} else static if (__traits(isPOD, typeof(` ~ VarName ~ 
`))) {` ~
          `writeln("` ~ VarName ~ ` ", " is a struct");` ~
       `} else static if (is(typeof(` ~ VarName ~ `) == int)) {` ~
          `writeln("` ~ VarName ~ ` ", " is an int");` ~
       `} else {` ~
          `static assert(false, "mxnTst Variable '` ~ VarName  ~ 
`' is of unknown type");` ~
       `}`
        ;
    }

    char char1;
    int  int1;
    byte byte1;

    struct foo {
       int  fooint;
       char foochar;
    }
    foo foovar1;

    mixin(mxnTst("char1"));   // Expected: char1 is a char. 
Actual: char1 is a char. (ok)
    mixin(mxnTst("int1"));    // Expected: int1 is an int.  
Actual: int1 is a struct. (FAIL)
    mixin(mxnTst("foovar1")); // Expected: foovar1 is a struct.  
Actual: foovar1 is a struct. (ok)
    mixin(mxnTst("byte1"));   // Expected: Run to fail with the 
static assert message. Actual: byte1 is a struct. (FAIL)
}
```


More information about the Digitalmars-d-learn mailing list