Thread overview
Why no implicit casting of class types?
Jun 08, 2005
Sean Kelly
Jun 08, 2005
clayasaurus
Jun 09, 2005
Sean Kelly
June 08, 2005
I'm just curious why this doesn't work:

# class C
# {
#     int opCast() { return val; }
#     int val;
# }
#
# void main()
# {
#     C c = new C();
#     int i = c;
# }


Sean


June 08, 2005
Sean Kelly wrote:
> I'm just curious why this doesn't work:
> 
> # class C
> # {
> #     int opCast() { return val; }
> #     int val;
> # }
> # # void main()
> # {
> #     C c = new C();
> #     int i = c;
> # }
> 
> 
> Sean
> 
> 

D makes casts obvious. Just use 'int i = cast(int)c;'
June 09, 2005
"Sean Kelly" <sean@f4.ca> wrote in message news:d87dlo$2bjs$1@digitaldaemon.com...
> I'm just curious why this doesn't work:

Because they're "evil."

Though I can understand where Walter is coming from.  There are some cases where implicit casting can really so some strange and undesired things (in some cases eliminating the safety of a strongly-typed language), but for things like value classes, having to explicitly cast can be a real pain. Especially when you're only allowed one opCast() per class.


June 09, 2005
I'd really like a way to fix that.  Even if it was so far as:

void* opCast(TypeInfo destinationType)
{
...
}

Where it could still support a simple:

int opCast()
{
...
}

But, I'm not sure what would be better than that... :/.  Must be something.  Maybe allowing return type overloading just in that case, but that would be confusing.

-[Unknown]


> Especially when you're only allowed one opCast() per class.
June 09, 2005
In article <d886ju$1iq$1@digitaldaemon.com>, Jarrett Billingsley says...
>
>"Sean Kelly" <sean@f4.ca> wrote in message news:d87dlo$2bjs$1@digitaldaemon.com...
>> I'm just curious why this doesn't work:
>
>Because they're "evil."
>
>Though I can understand where Walter is coming from.  There are some cases where implicit casting can really so some strange and undesired things (in some cases eliminating the safety of a strongly-typed language), but for things like value classes, having to explicitly cast can be a real pain. Especially when you're only allowed one opCast() per class.

True enough.  So how about this:

# class SpecialInt : int {
#     int opConv() {
#         return val;
#     }
#     int val;
# }

Here, the class is specifically declared as a value type.  opConv is called when performing implicit conversions.  This would not change the existing conversion rules, as a class is already implicitly convertible to its base class.  This could still be used for "evil" but perhaps not so much as if implicit conversion were allowed in the language as a whole.  It also allows us to easily extend value types with useful functionality.


Sean