cast()x - a valid expression?

Steven Schveighoffer schveiguy at yahoo.com
Wed Jun 1 13:05:57 PDT 2011


On Wed, 01 Jun 2011 15:38:32 -0400, Andrej Mitrovic  
<andrej.mitrovich at gmail.com> wrote:

> It seems to do even more than that:
>
>     int a;
>     const int b;
>     immutable int c;
>     shared int d;
>     shared(const int) e;
>
>     static assert(is(typeof(cast()a) == int));
>     static assert(is(typeof(cast()b) == int));
>     static assert(is(typeof(cast()c) == int));
>     static assert(is(typeof(cast()d) == int));
>     static assert(is(typeof(cast()e) == int));
>
> Talk about stealing the storm from std.traits.Unqual..
>
> On 6/1/11, KennyTM~ <kennytm at gmail.com> wrote:
>> While checking the Phobos source I've found an interesting expression
>>
>>        cast()(result[i]) = to!(E)(e);
>>
>> The 'cast()' means 'cast to mutable', e.g.
>>
>>        class S {}
>>        void g(S x) {}
>>        void main() {
>>           const S s;
>>           g(cast()s);
>>        }
>>
>> But this is not documented in the D spec (CastParam cannot be empty). Is
>> this an "accept-invalid" bug, or just a feature not yet documented?
>>
>>

It gets even better:

char[] x = "abc".dup;

assert(is(typeof(cast(const)x) == const(char[]));

I think you may have found a "bug" that should be a feature.  It's like  
dmd is organically growing features that we might need ;)  Is this  
software evolution?  Scary!

When will dmd decide that human life is a disease to be eradicated?  When  
will the world be dominated by constinators?!!!  I fear for my children.

All kidding aside, I actually think the syntax makes sense.  You are  
adding/removing modifiers, so just leave the type out of it.  The only  
drawback is, you can't do a cast directly to a tail-const array, but  
that's not a huge deal, since const(T[]) implicitly casts to const(T)[].

I dub this feature "Type Modifier Casting".

-Steve


More information about the Digitalmars-d mailing list