compile-time explicitness

Steven Schveighoffer schveiguy at yahoo.com
Fri Sep 23 10:25:29 PDT 2011


On Fri, 23 Sep 2011 12:20:21 -0400, Gor F. Gyolchanyan  
<gor.f.gyolchanyan at gmail.com> wrote:

> Not qite.

I apologize, you are right that __ctfe is a runtime variable, but I find  
that interesting.

An optimizer will (hopefully) remove any if(__ctfe) branches, so even  
though it's "evaluated at runtime", it's still evaluates to the constant 0.

The only difference is, you cannot use it to for instance change the  
structure of a struct during compile time.  And actually, thinking about  
it, this has to be this way.

For instance, what if you had:

struct S
{
    static if(__ctfe)
      int x;
    int y;
}

enum S s = S(1, 2);

The expression is evaluated at compile-time, but then the result can be  
used during runtime.  How does that work?

I think actually __ctfe as defined is the correct thing to have.  static  
if has too much power to change type layouts and would wreak havoc with  
the CTFE model.

So I guess I was wrong, and it's a good thing I was :)

> __ctfe can solve many problems, but, for example, you can't use __ctfe
> to determine whether you should use to!string or toStringNow.

You could:

if(__ctfe)
    to!string(x); // optimized out at runtime
else
    toStringNow(x); // optimized out at compile-time (well doesn't really  
matter)

> __ctfe can't allow you to have both compile-time and run-time versions  
> of the
> function body simultaneously.

The optimizer should remove any if(__ctfe) in the normal runtime function,  
since it's equivalent to if(0).  So yes, you can have two different  
versions.

For an example, see std.array.Appender's methods

> __ctfe can't help make non-functional-programming style templates.

I'm not sure what you mean by this.

> __ctfe can't allow you to define temporary locals to store intermediate  
> results of
> computation with template parameters, which can then be used in a static  
> if.

you can use enum for that already.

-Steve


More information about the Digitalmars-d mailing list