Inferred Type for Explicit Cast

Jonathan Marler via Digitalmars-d digitalmars-d at puremagic.com
Sat Dec 20 00:36:13 PST 2014


On Friday, 19 December 2014 at 15:17:04 UTC, Steven Schveighoffer 
wrote:
> On 12/18/14 6:18 PM, Adam D. Ruppe wrote:
>> On Thursday, 18 December 2014 at 23:06:12 UTC, ketmar via 
>> Digitalmars-d
>> wrote:
>>> the only thing this will help is to hide bugs, i believe.
>>
>> On the contrary, I find explicit casts hide bugs. Suppose you 
>> write:
>>
>> size_t a = cast(int) b;
>>
>> It will compile and run. It'll mostly work. But the cast to 
>> int probably
>> wasn't intended (it was probably written in 32 bit code and not
>> correctly ported to 64 bit).
>>
>> How often do we also write auto a = cast(T) b;? The difference 
>> would be
>> the type is written on the left side instead of the right. 
>> Might make an
>> important differnce when calling functions.
>>
>> I think the auto cast is a win all around.
>
> I have to agree with ketmar. Cast needs fixing, but this is not 
> it. We need more control over what is cast, not less control.
>
> Your example unwittingly shows the issue :) casts are blunt 
> instruments that force the compiler to abandon it's checks. I'm 
> not as concerned about a changing it's type as I am about b. 
> Change the type of b, and the compiler still happily generates 
> possibly disastrous code.
>
> At this point, we can only say "abandon ALL checks." We can't 
> finely tune this. I think we need something more along the 
> lines of C++'s casting directives.
>
> And in answer to your above code snippet, I see no benefit for:
>
> size_t a = cast(auto) b;
>
> over:
>
> auto a = cast(size_t) b;
>
> -Steve

Nobody likes to use cast, but for now we are stuck with it.  
Creating alternatives to cast would be a great thing to discuss 
but doesn't really apply to the point at hand, which is, would 
cast(auto) be a useful extension to our current cast operator?  I 
think it could be.  In my opinion, if we allow return value types 
to be written as "auto" then it makes since to have cast(auto) as 
well.  In both cases the developer would need to look somewhere 
else to find what type "auto" actually gets resolved to.

The way I look at it, cast(auto) is like saying, "hey compiler, I 
know this value can't be implicitly converted so just pretend 
like I've given you an explicit cast to whatever type you need".  
Note that this cast is still under the constraints of an explicit 
cast.  You can't cast a struct to an int or whatever. I can't 
really think of a case where this would be more dangerous than a 
typed explicit cast but I didn't think too long:)


More information about the Digitalmars-d mailing list