How to check if object is an instance of generic class?
ag0aep6g via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed May 3 11:04:20 PDT 2017
On 05/03/2017 07:26 PM, Nothing wrote:
> Equality checking is where I stuck. It should work as follows:
> 0. If we compare the Box [b]b[/b] to an object [b]o[/b] that is not an
> instance of Box, it should return false.
> 1. Empty boxes are equal no matter the type.
> 2. If type of payload for two boxes they're not equal.
> 3. If both boxes hold values of same types their payload is compared and
> it is the final result.
>
>
> Box!string() == Box!bool() -> true
> Box!int(1) == Box!Int(1) -> true
> Box!int(1) == Box!Int(2) -> false
>
> So is there an idiomatic approach to know if the Object is an instance
> of Box (regardless of content type T) and than if necessary to know
> exactly if two boxes have same concrete type T?
No. You can check if a type is an instance of the Box template, but that
doesn't help you here because you're dealing with `Object`. From there
you can only get back to Box!Foo when you know Foo.
You can add a common non-templated interface for all different Box types.
----
interface BoxI
{
bool isEmpty();
}
class Box(T) : BoxI
{
/* ... */
}
----
Now you can cast to BoxI, and call isEmpty. Which is all you need to do
your steps 0 and 1. For steps 2 and 3, you cast to the Box type at hand,
i.e. `Box!T` or just `Box`.
More information about the Digitalmars-d-learn
mailing list