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 10:54:13 PDT 2017


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 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.

Have a look at std.variant.Variant and std.typecons.Nullable. The
combination of these two may already do what you want.

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
			}
		}
		...
	}

However, this requires that the types of the incoming objects are known
beforehand. If you're using runtime polymorphism and don't know the
concrete types of the incoming Boxes beforehand, you could do this:

	class Box(T) {
		T t;

		bool opEquals(Object o)
		{
			auto p = cast(typeof(this)) o;
			if (p is null) {
				// This means either o is not a Box
				// type, or it has a different content
				// type: Box!A and Box!B are considered
				// to be distinct types at runtime in
				// spite of their common origin in the
				// same template.
				return false;
			}
			// Here, p !is null meaning that o must be an
			// instance of Box!T with the same T as this
			// object. So you could just compare them
			// directly.
			return t == p.t;
		}
	}


T

-- 
Век живи - век учись. А дураком помрёшь.


More information about the Digitalmars-d-learn mailing list