Is opCast need, we have to!

Jesse Phillips jessekphillips+D at gmail.com
Wed Dec 1 19:02:17 PST 2010


foobar Wrote:

> IMHO, coercions in D should be redesigned. They are a tiny bit better than C but C is a weekly (and poorly) typed language. I personally prefer the properly strongly typed ML family of languages.
> 
> My preference is as follows:
> 1. static_cast: 
>   a. Remove ALL implicit coercions inherited from c such as double -> int,

Done

>   b. I don't see the need for an operator for conversions since they can have different parameters, e.g.:
>   - converting to string can have formatting specified
>   - converting string to numeric types with optional base parameter
>   - converting integer to floating point specifies round/floor/ceiling/etc..

This was kind of my point, to! already specifies how to generically (an important part) to other types. And opCast overrides everything (which I don't wish to claim is incorrect, just asking).

> 2. const_cast: should be a _separate_ operator in order to prevent removing const by mistake.
>   const Base obj1 = new Derived();
>   auto obj2 = cast(Derived)(obj1); // oops: meant to only down cast

I think to! should be changed such that this would be a ConvException.

> 3. dynamic_cast: the language should provide a down cast operator for OO. 

Then the example above is invalid, though still valid when casting const double to int...

> 4. reinterpret_cast: unsafe and should be restricted as much as possible (Not available in @safe code) maybe not provide it at all since it's implementable via union. A restricted library solution for when you really want to play with bits and bytes? 
> 
> the above means that:
> double pi = 3.14; 
> int p = pi; // compile-time error

Currently is an error.

> int p = floor(pi); // ok

Maybe std.math.floor should return an int, since they are implicitly converted to real...

> and also:
> int x = ??; // some number
> double y = x; //compile-time error
> double z = double(x); // explicit

Other than overflow, which isn't fixed if made explicit, I don't see an issue with it being implicit.

> double r = 5 / 2; // compile error

Well this might be one, if 5 and 2 are variables.

> choose either:
> a.  double r1 = double(5/2); // 2.0
> b. double r2 = double (5) / 2; // 2.5

Assuming variables here, wouldn't that need to be:

double r2 = cast(double) 5 / cast(double) 2; // not implicit casting remember.


More information about the Digitalmars-d mailing list