On Saturday, 12 October 2013 at 05:38:16 UTC, Jonathan M Davis wrote:
On Friday, October 11, 2013 22:31:25 Jonathan M Davis wrote:
On Saturday, October 12, 2013 00:54:48 luminousone wrote:
> The inability to handle null is pretty big, specially > considering
> that at not point is the class instance itself cared about!,

No. It's expected. When you are casting to a particular object to test whether the object is of that type, you are testing the type that the object is, and if the object is null, then it is _not_ of the type that
you're casting to.
> Again this should be done via reflection, this method above > is
> hackish at best.

Testing via compile-time reflection is testing for something fundamentally different than what casting is testing for. With casting, you're testing whether the object is the type that you're casting to or a type derived from the type that you're casting to. With compile-time reflection, you're testing whether a particular type is derived from another type. One is testing an instance. The other is testing a type. The two are completely
different.

I'd also point out that if you have

class A
{
}

class B : A
{
}

B is _not_ an instance of A. It's a subclass of A. An instance is an object in
memory, not the type of the object.

auto a = new A; //instance of A
auto b = new B; //instance of B
A c = new B; //instance of B
A d; //There is no instance here. The reference is null.
B e; //There's no instance here either for the same reason.

So, you're using the term "instance of" incorrectly.

- Jonathan M Davis

I was using the terminology used in prior posts, my point was to the original intent of the poster.

And again, the casting solution is a bloody hack, it is loaded with corner cases that will break things if you are not aware of them. It also requires an allocated instance of that object, What the poster wishes to test for doesn't require that, so why have a function that needs it unnecessarily.

It is bad practice.

And I suppose in good faith of correcting bad practices,

bool inheritsFrom(A, B)( )
   if( is( A == class ) && is( B == class ) ) {
   if( __traits( isSame, A, B ) )
      return true;
   foreach( k, v ; BaseClassesTuple!A ) {
      if( __traits(isSame, B, v ) )
         return true;
   }
   return false;
}

Reply via email to