Re: How to check if object is an instance of generic class?
On Wednesday, 3 May 2017 at 17:54:13 UTC, H. S. Teoh wrote: On Wed, May 03, 2017 at 05:26:27PM +, Nothing via Digitalmars-d-learn wrote: Hi, Honestly I am new to D and templates system so excuse me But of course, if you wish to write your own Box type, then to answer your question: [...] 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? If the types of the Boxes are known at compile-time, you could make opEquals a template, like this: class Box(T) { T t; bool opEquals(U)(U u) { static if (is(U == Box!V, V)) { if (is(V == T)) return t == u.t; // Has the same content type else return false; // Has different content types } else { return false; // not a Box!T instantiation } } ... } Thx for your input. Yes the types are known at compile-time. However I tried something like your suggestion and it doesn't seem to work. I tried adding a writeln like this: writeln("entering opEquals"); At the start of opEquals's body and apparently when I use b1 == b2 it is not invoked.
How to check if object is an instance of generic class?
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.