Struct initializers and const in 2.009

Sean Kelly sean at f4.ca
Mon Jan 7 07:15:32 PST 2008


torhu wrote:
> Dan wrote:
>> You actually managed to make your programs compatible with D 1.x and 
>> 2.x !?!?
> 
> Only some bindings to a C library, so no classes or const methods 
> necessary.
> 
>> I spent a good 40 minutes on my source, and ultimately realized it's 
>> impossible for me to do so;
>>
>> version(D_Version2)
>>   alias const(char)[] const_string;
>> else
>>   alias char[] const_string;
>>
>> Value {
>>   const Value opIndex(const_string){
>>     bla bla   }
>> }
>>
>> You can't alias out the const declaration for the function, and you 
>> can't get rid of it in 2.x and still have the program work, let alone 
>> have the desired functionality.
> 
> Maybe you could make it work with some casting, but it might not be 
> worth it.  The const_string alias will work if you use a string mixin:
> 
> version(D_Version2)
>    mixin("alias const(char)[] const_string;");
>  else
>    alias char[] const_string;
> 
> But are you sure you need this, won't the Phobos string alias work? It's 
> defined in object.d.

You don't need either one for the function parameter.  Try this:

     ... opIndex( in char[] ) {}

I've come to the conclusion that the string aliases are really of fairly 
little utility in D, since 'in' works just as well for specifying const 
behavior and is also 1.0 compatible.  About the only place I've found 
myself using them for portable code is the return value of the toString 
routine, since there is no portable way to define a const return value 
other than an alias with string mixins, as above.


Sean



More information about the Digitalmars-d mailing list