rtti cast
BCS
BCS at pathlink.com
Wed May 7 08:34:47 PDT 2008
terranium wrote:
> BCS Wrote:
>
>
>>In most cases forgetting to check the cast return will result in an
>>seg-v from a dereferenced null because you almost always use it as the
>
>
> In most cases... almost always... When an invalid cast occurs,
it is not an error.
Thinking about it, I can't recall ever casting to a derived type where a
failed cast was an indication of a bug. In the few times I have done it,
it has always been in the context of "if a is'a B then" (and not just in
the code but in the proper function of the program as well).
>>Having the "bad cast" -> null is very handy when you don't known if the
>>cast will be good. It mean you can test it without invoking the
>>exception system and all the overhead that entails.
>
>
> maybe in this case we need some syntax sugar, not a silent cast?
a little sugar for the other way might be even handier
// not tested
template Force_Cast(T)
{
T Force_Cast(U)(U u)
{
static assert(is(U : T), "cant cast from " ~
U.stringof ~ " to " ~ T.stringof);
if(auto t = cast(T)u)
return t;
else
throw new
InvalidCastException("failed cast from " ~
U.stringof ~ " to " ~ T.stringof);
}
}
More information about the Digitalmars-d
mailing list