static if and templates

Christian Kamm kamm.incasoftware at shift-at-left-and-remove-this.de
Thu Sep 27 03:06:01 PDT 2007


Oliver wrote:

> bool isArray(T)(T expr){
> return (expr.mangleof)[0] == 'A';
> }
> 
> bool isMatrix(T)(T expr){
> static if ( (expr.mangleof)[0] == 'A' ) // works
> //static if ( isArray(expr) )  // does NOT work
> return (expr.mangleof)[1] == 'A';
> else
> return false;
> }

Static if requires the condition to be evaluated at compile time, but expr
is a run time construct. You can make these two compile-time evaluateable
by switching to templates:

---
import std.stdio;

template isArray(T){
    const isArray = (T.mangleof)[0] == 'A';
}

template isMatrix(T){
    static if ( isArray!(T) )
        const isMatrix = (T.mangleof)[1] == 'A';
    else
        const isMatrix = false;
}

void main () {
    double s = 1.;
    double[] v = [1.,2.];
    double[][] m = [[1.,2.]];

    writefln("s: ", isArray!(typeof(s)), " ", isMatrix!(typeof(s)) );
    writefln("v: ", isArray!(typeof(v)), " ", isMatrix!(typeof(v)) );
    writefln("m: ", isArray!(typeof(m)), " ", isMatrix!(typeof(m)) );
}



More information about the Digitalmars-d-learn mailing list