Non compile time evaluation for initializers

Steven Schveighoffer schveiguy at yahoo.com
Mon Oct 29 07:09:30 PDT 2007


"Max Samukha" wrote
> On Fri, 26 Oct 2007 15:45:45 +0200, Lutger
> <lutger.blijdestijn at gmail.com> wrote:
>
>>Max Samukha wrote:
>>> On Fri, 26 Oct 2007 10:52:25 +0200, Lutger
>>> <lutger.blijdestijn at gmail.com> wrote:
>>>
>>>> Lutger wrote:
>>>>> Janice Caron wrote:
>>>> ...
>>>>> Suppose this is implemented, then how can you achieve constant folding
>>>>> with CTFE in initializers? Since it is not a compile time context
>>>>> anymore, all functions that substitue y will be evaluated at runtime.
>>>> Nevermind, I responded too soon and overlooked the proviso that it's
>>>> only rewritten when it doesn't compile, sorry.
>>>
>>> Then if a compile time function is messed up in a way that makes it
>>> unevaluatable at compile time, it would be silently used at run-time,
>>> which is not desired?
>>
>>Hmm yes, it's still an issue. Some functions are quite inefficient for
>>example if they are made to be evaluated at compile time, which doesn't
>>matter in that context but does for the runtime case.
>
> As Reiner mentioned, the problem is that static variables should not
> be initialized at compile-time at all. If you want CTFE put the
> initializers in const context.
>
> int foo()
> {
>   return 1;
> }
>
> static int x = foo; // module scope, static is optional; foo would be
> evaluated on module construction
>
> class C
> {
>   static x = foo; // ditto
> }
>
> void bar()
> {
>  static x = foo; // ditto
> }
>
> Then 'static' keyword here would mean 'global' and compile time
> constructs would have to be changed to 'const if', 'const assert', etc
> (Don't beat me please!)

I'm not sure that const = CTFE/static = runtime is the right answer.  My 
original idea was that the compiler would decide if it could evaluate the 
rvalue at compile time, and do so if possible, but if not possible, use a 
static constructor to initialize the variable.  The current behavior is to 
have a compile-time error.

I understand your concern that when a CTFE is desired, you will not be able 
to tell whether the compiler decided to do it or not, but in all cases I can 
think of:

1. if you don't get CTFE, the evaluation is only a 1 time hit, at the 
beginning of the program.
2. If the compiler can't do CTFE, then it's probably because the rvalue 
cannot be evaluated at compile time no matter how you code it.
3. Most of the time, the static constructor form is what you really meant, 
but the compiler is forcing you to type it out that way.

To address this concern, could there be some sort of compile message, like a 
pragma that tells the compiler it should be able to do CTFE on an rvalue?

-Steve 





More information about the Digitalmars-d mailing list