Fastest way to check if the bottom-class of a class reference is any of a set of classes

H. S. Teoh hsteoh at quickfur.ath.cx
Mon Dec 16 17:19:37 UTC 2019


On Mon, Dec 16, 2019 at 02:38:59PM +0000, Per Nordlöw via Digitalmars-d-learn wrote:
> What is the fastest way to check whether a class reference is an instance of
> a
> bottom equal to any in a set of classes? My current try is something like
> 
> class C {}
> 
> class X : C {}
> class Y : C {}
> class Z : C {}
> ...
> 
> bool pred(scope const Object object)
> {
>     return (cast(const(X))object ||
>             cast(const(Y))object ||
>             cast(const(Z))object ||
>             ...);
> }
[...]

What about:

	class X {}
	class Y {}
	class Z {}

	bool pred(scope const Object object)
	{
		import std.meta : AliasSeq;

		// make this as long as you need
		alias MyClasses = AliasSeq!(X, Y, Z);

		static foreach (C; MyClasses)
		{
			if (cast(const(C)) object) return true;
		}
		return false;
	}


T

-- 
Beware of bugs in the above code; I have only proved it correct, not tried it. -- Donald Knuth


More information about the Digitalmars-d-learn mailing list