Semantics of ^^, Version 3 (Final?)

Don nospam at nospam.com
Wed Dec 9 02:51:40 PST 2009


Don wrote:
> Rainer Deyke wrote:
>> Don wrote:
>>> Rainer Deyke wrote:
>>>> Not quite.  Under the proposal, -1^^-1 works (i.e. produces the correct
>>>> result) at compile time but fails at runtime.
>>> It won't pass CTFE.
>>
>> pure int f() { return -1; }
>> void g(int)(int);
>> g!(f() ^^ f())(0); // Works.
> 
> No, it doesn't work. It's exactly the same as:
> 
> int intpow(int x, int y)
> {
>    assert(y>=0);
>    return x;
> }
> 
> g!(intpow(f(), f())(0);
> 
> 
> f() ^^ f() is not a constant expression. It won't get transformed. It 
> can be *interpreted* at compile time, but that'll generate an error.
> 
> 
>> g!(0)(f() ^^ f()); // Runtime error?
> 
> Definitely.
>>
>> 'f() ^^ f()' can be a compile-time constant, but isn't guaranteed to be
>> evaluated at compile time.
> 
> No, it's not a compile-time constant, unless it's turned into one.
> 
> If however you changed it to:
> 
> template eval(int x) {  enum int eval = x; }
> 
> g!( eval!(f()) ^^ f() )(0);
> 
> which turns f() into a compile-time constant, then it'd work.
> But then it'd work at runtime, as well.

You can see this effect in action in the current version of DMD, because 
at present sqrt() can be evaluated at compile time, but pow() cannot be.
(this behaviour will be fixed, but for now it illustrates the point).

-----------

import std.math;

int bar(double x)() { return 0; }

double foo() { return 0.5; }

void main()
{
    int z = bar!( 7.0 ^^ 0.5 )();  // works -- 0.5 is a constant
    int z2 = bar!( 7.0 ^^ foo() )(); // fails -- foo() is not.
}



More information about the Digitalmars-d mailing list