On Saturday, 12 October 2013 at 07:47:18 UTC, Jonathan M Davis
wrote:
On Saturday, October 12, 2013 09:32:09 luminousone wrote:
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
Of course, it requires an instance of the object. The point is
to test whether
an instance is of a type derived from a particular type, not
whether a
particular type is derived from a particular type. If the OP
wants to test
whether a particular type is derived from another type, then
casting is not
the right solution. The way to do that is to use an is
expression, e.g.
is(Derived : Base). If you really care that the type is a
derived type and
want to avoid any other type of implicit conversions, then you
need to use
some compile time reflection to do that, but that's often
overkill and
completely kills the ability to create class which "inherits"
via alias this,
which is the main purpose for alias this existing in the first
place.
It is bad practice.
It's standard practice. Both the online docs and TDPL will tell
you to use a
cast to determine whether a particular object's type is derived
from a
particular type. And I completely disagree that it's bad
practice, but clearly
we're not going to agree on that.
- Jonathan M Davis
1.
opCast, and alias can break the cast approach. You pointed this
out yourself.
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));
}
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.
Again it is bad practice regardless of what any document says.