On Saturday, 20 December 2014 at 10:14:10 UTC, bearophile wrote:
Jonathan Marler:
if we allow return value types to be written as "auto" then it
makes since to have cast(auto) as well.
I think "cast(auto)" as I understand in your proposal
introduces too often undefined situations, because in many
cases the compiler can't know what's the type to cast to, and
guessing is not acceptable. So I think it's not a good idea.
You gave one example of an 'undefined situation' (auto y =
cast(auto)x). However this situation is clearly an error (not
undefined). I think what you meant was that the type of auto is
undefined, not the situation itself. To this you are correct. I
fail to see why that makes this a bad idea. The whole concept of
'auto' is not defined in many situations but that doesn't make it
a bad idea. If you were a programmer and you declared a variable
y using auto, why would you think you need to cast it?
int x;
auto y = x; // Normal
auto y = cast(int)x; // huh? there's not reason to do this
The only reason I could think of is when you want to explicitly
say what type y should be. But why would you do that using a
cast? Just declare y as the type you want to be and skip 'auto'.
byte y = cast(byte)x;
Ah but now you have to keep the type of y and the cast "in sync".
So you could write this;
auto y = cast(byte)x;
It looks a little weird but it works. I however think that if
you want y to be a specific type, you should declare it as such
(instead of using auto).
byte y = cast(byte)x;
We're back to the previous example. However now we are faced with
the same problem of keeping the 2 types in sync. You could use
cast(typeof(y)) to solve this, or you could use cast(auto).
byte y = cast(typeof(y))x;
byte y = cast(auto)x;
cast(auto) looks nicer but both work fine. The problem with
cast(typeof(y)) is that it doesn't work when you are assigning x
to an unnamed variable (like a function argument).
But sometimes I have code like this:
void main() {
int x;
byte y;
// ...
y = cast(typeof(y))x;
}
Here I want to cast x to the type of y to allow the assignment
to y. This is perhaps an acceptable semantics for "cast(auto)":
void main() {
int x;
byte y;
// ...
y = cast(auto)x; // OK
}
In that case the inference for the casting type is easy because
the type of y is already defined. More examples:
void foo(byte z) {}
void main() {
int x;
// ...
auto y = cast(auto)x; // Error
byte y = cast(auto)x; // OK, but not very useful
foo(cast(auto)x); // OK
}
Bye,
bearophile-
Lastly I would like to say that cast(auto) provides a bit of
functionality that is currently nowhere in the language. It's
not the same as cast(typeof(var)) since that cast needs a named
variable to refer to. It would provide some functionality for
templates that are currently nowhere in the langauge. I haven't
thought of an example yet but if you think of one let me know:)