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 12:56:59 PDT 2017


On Wednesday, 3 May 2017 at 17:54:13 UTC, H. S. Teoh wrote:
> On Wed, May 03, 2017 at 05:26:27PM +0000, 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.


More information about the Digitalmars-d-learn mailing list