Traits

Jonathan M Davis jmdavisProg at gmx.com
Sat Oct 12 01:40:33 PDT 2013


On Saturday, October 12, 2013 10:24:13 luminousone wrote:
> 1.
> 
> opCast, and alias can break the cast approach. You pointed this
> out yourself.

And as I pointed out, that's perfectly acceptable in most cases, because what 
you care about is the conversion. alias this is specifically designed with the 
idea that you can subtype a struct or class with it. Checking with typeid to 
get the exact type would be circumventing that design. So, casting is almost 
always the correct option.

> 2.
> 
> The requested function is testing types not instance state.
> 
> bool instanceOf(A,B)( B value ) {
>          assert( value !is null );
>          return inheritsFrom(A,typeof(value));
> }

Fine. That doesn't invalidate casting to check an instance. They're two 
different things.

> 3.
> 
> Cast breaks on null, so this must be checked on every call, and
> leads to a 3 state outcome, true, false, and null, null then
> returns false, which is potentially incorrect and could cause odd
> bugs hard to trace.

null is _supposed_ to be false. The whole point is to check whether the object 
in question can be used as the type that you're casting to. If it's null, it 
isn't the type that you're casting to - it's null. So, false is exactly what 
it should be doing. It's specifically designed so that you can do

if(auto c = cast(MyClass)obj)
{
    ...
}

> Again it is bad practice regardless of what any document says.

And I completely disagree. Casting is doing precisely what it's designed to 
do, and I really don't see a problem with it.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list