Inferred Type for Explicit Cast
Steven Schveighoffer via Digitalmars-d
digitalmars-d at puremagic.com
Sat Dec 20 19:04:12 PST 2014
On 12/20/14 3:36 AM, Jonathan Marler wrote:
> 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.
You have to be careful here, when you think about who is in charge of what.
For an auto return, it is the function author who is deciding what auto
should resolve to. But cast(auto) is letting the author of the called
function dictate. This is a decoupling of who is responsible for the
type vs. who is requesting the cast.
Now, just 'auto' is fine, because you are not subverting the type
system, and unsafe behavior cannot result. But with something like
'cast', you are potentially playing with fire.
For instance, let's say you have a function which accepts an int, but
the author changes it later to accept a pointer to an int. You are
passing in a size_t, via cast(auto), now the compiler happily
reinterprets the size_t as a pointer, and you are in dangerous territory.
You can think of it this way. With cast(T), you are saying "I've
examined the possibilities of casting this value to type T, I know what
I'm doing". With cast(auto) you are saying "I'm OK with this value
casting to any other value that cast may work with. I know what I'm
doing." I find that the requirement of just typing "cast(auto)" does not
match the gravity of the analysis that is required to ensure that is true.
-Steve
More information about the Digitalmars-d
mailing list