Porting D 1.0 code to 2.0, 'const' -> 'invariant'

Steven Schveighoffer schveiguy at yahoo.com
Fri Jan 18 08:07:00 PST 2008


"Sean Kelly" wrote
> Robert Fraser wrote:
>> Sean Kelly wrote:
>>> Robert Fraser wrote:
>>>> Sean Kelly wrote:
>>>>> I know this issue has been discussed to death, but I'd like to once
>>>>> again question the rationale behind changing the meaning of the 
>>>>> 'const'
>>>>> keyword between 1.0 and 2.0, given that the choice of keywords for
>>>>> const
>>>>> features in 2.0 seems completely arbitrary.
>>>>>
>>>>> In D 1.0, 'const' is essentially the same as 'invariant' in D 2.0.
>>>>> It's
>>>>> true that 'const' works just as well for the average situation in D
>>>>> 2.0,
>>>>> but what if I have a ton of constants in a D 1.0 library that I want 
>>>>> to
>>>>> work the same way in D 2.0?  ie. in D 1.0 the 'const' label means I 
>>>>> can
>>>>> use the value without synchronization for multithreaded programming,
>>>>> etc.  In D 2.0, this role is filled by 'invariant' and 'const' has 
>>>>> been
>>>>> weakened to mean "read-only view," which is not at all the same thing.
>>>>>
>>>>> I suppose what I'm asking is how I should go about making a library
>>>>> maximally cross-compatible with D 1.0 and 2.0, given the changed
>>>>> meaning
>>>>> of 'const'?
>>>> Mixins.
>>>
>>> That suggests I should do something like this:
>>>
>>>     mixin("const") i = 5;
>>>
>>> But as far as I know, string mixins must be expressions or complete
>>> statements.  How would I declare a series of const values using mixins?
>>>
>>>
>>> Sean
>>
>> I was half-kidding since it would probably be a terrible solution. I was
>> thinking something like:
>>
>> char[] constant(char[] declaration)
>> {
>>     version(D_Version_2)
>>         return "invariant " ~ declaration ~ ";";
>>     else
>>         return "const " ~ declaration ~ ";";
>> }
>>
>> mixin(constant("i = 5"));
>
> Yeah, it would be pretty terrible :-)  But it'd do the trick in a pinch.
> I posted my message half out of frustration and half fishing for the
> cleanest way to do this in case we're stuck with things as they are.
>
>
> Sean

I know it's ugly, but for integral constants, you should be able to use enum 
consistently:

enum
{
  i = 5,
  ...
}

-Steve 





More information about the Digitalmars-d mailing list