How to check if object is an instance of generic class?

H. S. Teoh via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed May 3 11:04:39 PDT 2017


On Wed, May 03, 2017 at 08:04:20PM +0200, ag0aep6g via Digitalmars-d-learn wrote:
> On 05/03/2017 07:26 PM, Nothing wrote:
[...]
> > 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.

For opEquals, having an Object is sufficient. You just cast the Object
into the current type (Box!T for some concrete T), and if it's null,
then either it's not a Box type, or it's Box!U where U != T.  Presumably
if U != T then opEquals should just return false, so that's no problem.
If U == T, then you now have a reference with the right type that you
can use to compare the contents.

You only need a common interface if you wish to do something more with
Box!X instantiations that's common across all Boxes.


T

-- 
Meat: euphemism for dead animal. -- Flora


More information about the Digitalmars-d-learn mailing list