how to test if member of instance exists/defined?

H. S. Teoh via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Mar 22 13:56:19 PDT 2017


On Wed, Mar 22, 2017 at 08:35:27PM +0000, StarGrazer via Digitalmars-d-learn wrote:
> I've tried compiles but I guess that only checks if the code has valid
> syntax, not if it actually will compile in context.

I'm not sure what you mean by "member of instance", but if you mean
whether some given type T, presumably an aggregate like a struct, has
some member x, here's how to do it:

Code:

	struct StructA {
		int x;
	}
	struct StructB {
		int y;
	}
	template CheckMembers(T) {
		static if (is(typeof(T.init.x)))
			pragma(msg, T.stringof ~ " has member named x");
		else
			pragma(msg, T.stringof ~ " doesn't have a member named x");
	}
	alias dummy1 = CheckMembers!StructA;
	alias dummy2 = CheckMembers!StructB;

Compiler output:

	StructA has member named x
	StructB doesn't have a member named x

The key is to use is(typeof(...)) as the check.  The idea being that if
the member doesn't exist, then the compiler won't be able to find a type
for the member, so it will not have a valid type and is(...) will return
false. Whereas if the member does exist, then it will have some valid
type (and it doesn't matter what that type is) and is(...) will return
true.

Generally, using is(typeof(...)) is preferable to using
__traits(compiles, ...) where possible.


T

-- 
If Java had true garbage collection, most programs would delete themselves upon execution. -- Robert Sewell


More information about the Digitalmars-d-learn mailing list