rtti cast

Leandro Lucarella llucax at gmail.com
Mon May 5 07:35:30 PDT 2008


Jarrett Billingsley, el  2 de mayo a las 16:40 me escribiste:
> For that matter, some languages (like C#) have both kinds of casts - one 
> that throws an exception and one that doesn't.  Either can really be 
> implemented in the other, but the null-returning kind is more basic and 
> efficient. 

C++ have the 2 too. If you cast a pointer, it returns NULL if the cast
fails but if you cast a reference, the cast throws a bad_cast exception if
it fails.

Unfortunatelly this can't be done in D (at least in an elegant way) because
it's reference semantics for objects. But I thinks std.contracts.enforce[1]
is a perfect solution for this:

auto y = enforce(cast(D)x);
// y is not null from here on

Or just use assert if you want the check to be gone in release builds:
auto y = cast(D)x;
assert(y !is null);

[1] http://www.digitalmars.com/d/2.0/phobos/std_contracts.html

-- 
Leandro Lucarella (luca) | Blog colectivo: http://www.mazziblog.com.ar/blog/
----------------------------------------------------------------------------
GPG Key: 5F5A8D05 (F8CD F9A7 BF00 5431 4145  104C 949E BFB6 5F5A 8D05)
----------------------------------------------------------------------------
The number of wars fought between countries
That both have at least one McDonalds is zero



More information about the Digitalmars-d mailing list