Const template

Sean Kelly sean at f4.ca
Tue Jan 23 08:26:53 PST 2007


Frits van Bommel wrote:
> Sean Kelly wrote:
>> Lionello Lunesu wrote:
>>> 'const' is not always a compile time constant. A const in function or 
>>> in a class can have a different value for each call/instance. Don't 
>>> ask me why.
>>
>> I ran into this problem recently:
>>
>>     module a;
>>
>>     class C
>>     {
>>         const int val;
>>
>>         static this() { val = 1; }
>>     }
>>
>>     C:\code\src\d\test>dmd test
>>     test.d(7): Error: can only initialize const val inside constructor
>>
>> I'm sure this is a bug but haven't reported it yet.  Trying to use a 
>> static module ctor to init the class const doesn't work either.  But 
>> if the const is global then all is well.
> 
> I don't see how that is a bug in anything but your code. The error 
> message may be a bit unclear in this instance, but I believe it is still 
> correct.
> Note that it says you need to do it in a constructor, not in a *static* 
> constructor (or *module* constructor). You need a plain old constructor 
> to initialize that field. That, or the field should have been static.

Aren't const values implicitly static?  I assumed that they were.

> So you may have meant one of these:
> -----
>     class C
>     {
>         static const int val;
> 
>         static this() { val = 1; }
>     }
> 
>     class D
>     {
>         const int val;
> 
>         this() { val = 1; }
>     }
> -----
> The first is for if it's the same for all instances of the class, the 
> second if it doesn't change for the lifetime of an instance of the 
> class. Neither of these needs to be a compile-time constant; both can be 
> determined at runtime.

Very weird.  I had no idea that constants could be defined on a 
per-instance basis.  Thanks!


Sean



More information about the Digitalmars-d mailing list