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

Nothing via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed May 3 10:26:27 PDT 2017


Hi, Honestly I am new to D and templates system so excuse me if 
my question will seem trivial.

I want to develop a generic Box(T) class that can be either empty 
or hold a value of arbitrary type T.

//____________________
class Box(T)
{
     override bool opEquals(Object o)
     {
         //...
         return false;
     }

private:
     T t;
     bool empty;
public:
     this(T t)
     {
         this.t = t;
         empty = false;
     }

     this()
     {
         empty = true;
     }

     bool isEmpty()
     {
         return empty;
     }

     void set(T t)
     {
         this.t = t;
         empty = false;
     }
}

void main()
{
     Box!int b1 = new Box!int(1);
     Box!int b2 = new Box!int(2);
}
//_________________________


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?

Thanks.


More information about the Digitalmars-d-learn mailing list