How do I check if this field is of this template struct?

Jack jckj33 at gmail.com
Fri Mar 19 16:41:11 UTC 2021


On Friday, 19 March 2021 at 08:54:50 UTC, Paul Backus wrote:
> On Friday, 19 March 2021 at 07:14:46 UTC, Jack wrote:
>> give below template struct, how can I list the members x, y 
>> and z? I've tried something with OriginalType and TemplateOf 
>> but no luck... it seems if I do foo!"str1" the "str1" became 
>> "part of type"? give .stringof from typeof(__traits(getMember, 
>> foo, field)) I thought the type would be foo!string or 
>> something.
>
> You want std.traits.isInstanceOf:
>
>     static if(!isType!m && isInstanceOf!(foo, typeof(m)))

thanks this works fine outside a method but not in a static 
method. what am I missing?

void main()
{
         // doesn't print anything
	Foo.list();
}

alias Foo = foo!();

template foo(string s = null)
{
	@nogc
	struct foo
	{
		int n;

		enum x = foo!"str1"(10);
		enum y = foo!"str2"(20);
		enum z = foo!"str3"(30);

		enum myEnum { none }

		void someMethod() { }

		static void list()
		{
			//writeln("members = ", [__traits(allMembers, foo!())]);
			static foreach(field; __traits(allMembers, foo!()))
			{{
				alias m = __traits(getMember, foo!(), field);
				static if(!isType!m && isInstanceOf!(foo, typeof(m)))
				{
					writefln("field = [%s]", field);
				}
			}}
		}
	}
}



More information about the Digitalmars-d-learn mailing list