Runtime constant definitions

Lars Kyllingstad public at kyllingen.NOSPAMnet
Fri Sep 12 00:10:03 PDT 2008


Bill Baxter wrote:
> On Fri, Sep 12, 2008 at 3:14 PM, Lars Kyllingstad
> <public at kyllingen.nospamnet> wrote:
>> Hi,
>>
>> I'm trying to define a couple of constants that I want to be computed at run
>> time. I have written the following code:
>>
>> ---
>>
>> /// Square root of real-number precision.
>> final real REAL_EPSILON_SQRT;
>>
>> /// Cube root of real-number precision.
>> final real REAL_EPSILON_CBRT;
>>
>>
>> static this()
>> {
>>    REAL_EPSILON_SQRT = sqrt(real.epsilon);
>>    REAL_EPSILON_CBRT = cbrt(real.epsilon);
>> }
>>
>> ---
>>
>> Compiling this, I get the errors
>>
>> scid/core.d:21: Error: cannot modify final variable 'REAL_EPSILON_SQRT'
>> scid/core.d:22: Error: cannot modify final variable 'REAL_EPSILON_CBRT'
>>
>> where the lines 21 and 22 are the ones inside the curly braces. What's
>> wrong?
> 
> D1 or D2?

D1, using GDC.

> Does something in the spec lead you to believe that static this()
> should get around final's restrictions?

None other than the fact that the following compiles perfectly:

class Foo
{
     final real bar;

     this()
     {
         bar = 1.0;
     }
}

I thought the whole point of a final variable was that it becomes 
constant AFTER the first time one assigns a value to it.

> It does seem like there should be some way to make a module-level
> constant that requires some computation.

Agreed.

> But I'd say just make 'em non final.  Or use CTFE cbrt/sqrt functions.
>  Or just precompute the value.

The best would of course be to calculate the values at compile time. I 
didn't know that's possible in D. How do I do this?

Since real is an architecture-dependent type, I don't want to precompute 
the values.

-Lars


More information about the Digitalmars-d-learn mailing list