Is opCast need, we have to!

Jonathan M Davis jmdavisProg at gmx.com
Wed Dec 1 15:06:16 PST 2010


On Wednesday, December 01, 2010 14:32:12 bearophile wrote:
> foobar:
> > 1. static_cast:
> >   a. Remove ALL implicit coercions inherited from c such as double ->
> >   int, 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..
> > 
> > 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
> > 
> > 3. dynamic_cast: the language should provide a down cast operator for OO.
> > 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?
> 
> There are some ideas here, like the separation from const_cast, dynamic
> cast, and other casts. In past I too have asked for something similar, but
> I think Walter was not interested.
> 
> I guess the idea of having a single cast is to keep the language simple.
> But those _are_ different kinds of casts, they have different semantics.
> Lumping different semantics into the same syntax is not a good way to
> simplify a language, in my opinion. It just creates obscurity and maybe
> some other troubles too.

And how many programmers do you know who actually, really know the differences 
between the 4 C++ cast types. _I_'m not sure that _I_ know, and I've studied it. 
And honestly, in most cases - if not in _all_ cases - as far as I can tell, the 
compiler should be able to determine the correct cast type. So, forcing that on 
the programmer is just stupid. If you actually _need_ separate cast types, then 
we should have them, but if we can avoid that, we definitely should. I think that 
the fact that C++ has so many types of casts is horrible. I try and use them 
correctly, but I don't think that there are very many programmers (percentage-
wise at least) who do. I know plenty of programmers who just use C-style casts 
everywhere.

- Jonathan M Davis


More information about the Digitalmars-d mailing list