Safe cast

Виталий Фадеев vital.fadeev at gmail.com
Fri Mar 6 12:45:54 UTC 2020


On Friday, 6 March 2020 at 12:35:29 UTC, Виталий Фадеев wrote:
> Searching info for object casting with checking class type at 
> runtime.
>
> Like this:
>
> class A
> {
>     //
> }
>
> class B
> {
>     int bVar;
> }
>
>
> unittest
> {
>     A a = new A();
>
>     A x = cast( A )a;     // ok
>     A x = cast( B )a;     // ok, but unsafe
>     A x = safeCast( B )a; // throw exception
>     A x = safeCast( A )a; // ok
> }
>
>
> Searching some like next:
>
> T safeCast( CLS )( CLS o )
> {
>   ... // checking type of o
>   ... // may be check ClassInfo...
>   return T;
> }
>
> Has function like a safeCast() ?
> Or other solution ? ...


I using now next code:

import std.stdio;

class Base {}

class A : Base {}
class B : Base {}


T safeCast( T, CLS )( CLS o )
{
	if ( typeid( o ) == typeid( T ) )
		return cast(T)o;
	else
		throw new Exception( "casting error" );
}


void main()
{	
     Base a = new A();

     A x1 = cast( A )a;      // ok
     B x2 = cast( B )a;      // ok, but unsafe
     B x3 = safeCast!B( a ); // throw exception
     A x4 = safeCast!A( a ); // ok
}




More information about the Digitalmars-d-learn mailing list