Traits

luminousone rd.hunt at gmail.com
Sat Oct 12 02:50:27 PDT 2013


On Saturday, 12 October 2013 at 08:40:42 UTC, Jonathan M Davis 
wrote:
> 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


1.

Your hand waving corner cases.

2.

Your throwing away perfectly good opportunities for the compiler 
to use CTFE by depending on allocated instance state(or at least 
its address) to get your answers.

To say nothing of the fact, that reflection won't have the list 
of corner case problems that casting does.

Reflection is simply correct in more cases then casting for this 
activity, it is also more generic, and requires fewer function 
parameters.

3.

Hardly, casting null works perfectly fine in c and c++, D strives 
towards more correct code, its one of the things I love about the 
language.

It is precisely because D checks null on cast, that creates the 
potential ternary return. A corner case I grant you, but still.

Further D being a statically typed language, it could very well 
be argued, that a nulled reference, still has a type.

meaning...

bool instanceOf(A,B)( B value ) {
          return inheritsFrom(A,B);
}

would be more correct then using typeOf(value) version above.


More information about the Digitalmars-d-learn mailing list