On Wed, 01 Jun 2011 16:42:10 -0400, Nick Sabalausky <[email protected]> wrote:

"Steven Schveighoffer" <[email protected]> wrote in message
It gets even better:

char[] x = "abc".dup;

assert(is(typeof(cast(const)x) == const(char[]));

I think you may have found a "bug" that should be a feature.  It's like
dmd is organically growing features that we might need ;)  Is this
software evolution?  Scary!

When will dmd decide that human life is a disease to be eradicated? When
will the world be dominated by constinators?!!!  I fear for my children.

All kidding aside, I actually think the syntax makes sense.  You are
adding/removing modifiers, so just leave the type out of it.  The only
drawback is, you can't do a cast directly to a tail-const array, but
that's not a huge deal, since const(T[]) implicitly casts to const(T)[].

I dub this feature "Type Modifier Casting".


It's nice in a way, but it's all based on the way cast handles modifiers.
And I've always been a bit unconfortable with how that's handled (In fact, I
was just thinking about this yesterday). Specifically, it seems extremely
bad that it's so incredibly easy to accidentaly cast away things like const
and immutable:

Yes, it would be nice to have the equivalent of static_cast (which doesn't allow removing const in C++). I think however, we don't need compiler support for such things. We can probably do this via metaprogramming.

However, having the ability to cast away or to const/immutable/shared/inout is very close to const_cast in C++. It fixes the problem where you just want to cast away const but inadvertently end up switching the type.

We also need a static_cast for objects. Right now, casting to a derived object involves a dynamic lookup, but if you know that the dynamic lookup is not necessary, a cast which does not do a dynamic lookup can be much faster.

For example, I could have a class A that contains a member of type X. Then you implement B : A and Y : X such that B's member X is always actually a Y. Re-storing the Y as another member is wasteful, and so is doing a dynamic cast for every usage of the member.

Of course, you can probably use some fancy helper templates to make sure you preserve all modifiers. But needing to do so is just asking for mistakes: it seems like a huge violation of "make the right way easy, and the wrong way
hard".

I get what you are saying. I would be happy if default cast didn't allow casting away const or immutable, but I think we would have a difficult time introducing such a change.

Note however, C++ has good success with static_cast vs the old C-style cast (which is supported), so there is hope. The more troubling thing is when you *want* to do a dynamic cast (which can only be done via the cast(X) style), you can inadvertently remove const or immutable.

-Steve

Reply via email to