non-constant expression

Jarrett Billingsley kb3ctd2 at yahoo.com
Wed Jan 24 05:59:48 PST 2007


"Robby" <robby.lansaw at gmail.com> wrote in message 
news:ep7nbd$1r1i$1 at digitaldaemon.com...
> is there a way I can do this in the module scope? I would have thought 
> that since everything is known at compile time it would have flew, do I 
> need to go about it in a different manner, or?
>
> enum whatever
> {
> one,
> two,
> three }
> int whatever2(int x)
> {
> return 1<< x; }
>
> const int a = whatever2(whatever.one);
> int b = whatever2(whatever.one);
>
> testcode.d(11): Error: non-constant expression (whatever2)(0)
> testcode.d(12): Error: non-constant expression (whatever2)(0)

Nope, whatever2 is a function and as such can't be evaluated at 
compile-time.  However, you can use a template instead:

enum whatever
{
    one,
    two,
    three
}

template whatever2(int x)
{
    const int whatever2 = 1 << x;
}

const int a = whatever2!(whatever.one);
int b = whatever2!(whatever.one);

Note that whatever2 can then not be used as a function; it is always 
evaluated at compile-time, so you can't do something like

void main()
{
    int x;
    din.readf("%d", x);
    writefln(whatever!(x));
}

because then the const int inside whatever2 will have a non-constant 
initializer!

If you want whatever2 to be a function, you'll have to initialize your 
globals differently:

int whatever2(int x)
{
    return 1 << x;
}

const int a;
int b;

static this()
{
    a = whatever2(whatever.one);
    b = whatever2(whatever.one);
}

It looks weird, declaring a as a const and then assigning it in the static 
this(), but that's perfectly legal -- you can assign to constant values 
once, but that assignment can happen anywhere. 




More information about the Digitalmars-d-learn mailing list