digitalmars.D.learn - Safe cast
- =?UTF-8?B?0JLQuNGC0LDQu9C40Lkg0KTQsNC0?= =?UTF-8?B?0LXQtdCy?= (28/28) Mar 06 2020 Searching info for object casting with checking class type at
- =?UTF-8?B?0JLQuNGC0LDQu9C40Lkg0KTQsNC0?= =?UTF-8?B?0LXQtdCy?= (21/49) Mar 06 2020 I using now next code:
- drug (4/30) Mar 06 2020 Here x will be null. You can use `enforce(x !is null);` if you want
- Adam D. Ruppe (9/11) Mar 06 2020 or since enforce returns it thing, just do
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 ? ...
Mar 06 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
}
Mar 06 2020
It's too complex On 3/6/20 3:45 PM, Виталий Фадеев wrote:On Friday, 6 March 2020 at 12:35:29 UTC, Виталий Фадеев wrote:Here x will be null. You can use `enforce(x !is null);` if you want exception.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 unsafeA x = safeCast( B )a; // throw exception A x = safeCast( A )a; // ok }
Mar 06 2020
On Friday, 6 March 2020 at 13:03:22 UTC, drug wrote:Here x will be null. You can use `enforce(x !is null);` if you want exception.or since enforce returns it thing, just do B b = enforce(cast(B) x); you can also check easily in if statements: if(auto b = cast(B) x) { // x was a b, use b in here } else { // x was not b, try something else }
Mar 06 2020








Adam D. Ruppe <destructionator gmail.com>