Interesting GCC extensions

bearophile bearophileHUGS at lycos.com
Mon Sep 28 13:04:47 PDT 2009


Lutger:

> We don't need an extension for this! Look:
> 
> template Eval(string exp)
> {
>     enum Eval = mixin(exp);
> }
> 
> template IsConstant(string exp)
> {
>     enum IsConstant = __traits(compiles, Eval!exp);
> }


>From what I see I think your code is useless for my purposes:

// D2 code
import std.stdio: writeln;

template Eval(string exp) {
    enum Eval = mixin(exp);
}

template IsConstant(string exp) {
    enum IsConstant = __traits(compiles, Eval!exp);
}

template Tuple(T...) { alias T Tuple; }

template Range(int stop) {
    static if (stop <= 0)
        alias Tuple!() Range;
    else
        alias Tuple!(Range!(stop-1), stop-1) Range;
}

long ipow(long x, int n) {
    long result = 1;

    static if (IsConstant!("n")) {
        pragma(msg, "constant");
        static if (n < 5) {
            foreach (i; Range!(n))
                result *= x;
        } else {
            for (int i; i < n; i++)
                result *= x;
        }
    } else {
        pragma(msg, "not constant");
        for (int i; i < n; i++)
            result *= x;
    }

    return result;
}

enum int w = 5;
void main() {
    int x = 2;
    const int y = 3;
    enum int z = 4;
    writeln(IsConstant!("x"), " ", IsConstant!("y"),
            " ", IsConstant!("z"), " ", IsConstant!("w"));
    // prints: false false false true

    ipow(10, x);
    ipow(10, y);
    ipow(10, z);
}

Even "z" is seen as not constant?

Bye,
bearophile



More information about the Digitalmars-d mailing list