What's wrong with this template function?

Machine Code jckj33 at gmail.com
Thu Jan 3 18:49:01 UTC 2019


I wrote a small routine to return the first member of type T of a 
same type, like struct below, but the assert is reached albeit 
the "yes" message is printed. What am I missing? should I use 
something else than return keyword to return from a template 
function or what?

struct Color
{
	enum red = Color("red", 30);
	enum blue = Color("blue", 40);
	enum green = Color("green");

	string name;
	int value;
	alias value this;
}

the routine:

T first(T)()
{
	import std.string : format;
	pragma(msg, format!"types = %s"([__traits(derivedMembers, T)]));
	
	static foreach(field; [__traits(derivedMembers, T)])
	{
		// exit on first match
		pragma(msg, format!"member %s"(field));
		static if(is(typeof(__traits(getMember, T, field)) == T))
		{
			pragma(msg, "yes");
			return __traits(getMember, T, field);
		}
		else
		{
			pragma(msg, "no");
		}
	}
	import std.string : format;
	static assert(0,
		format!"no first member of type %s found"(T.stringof));
}


More information about the Digitalmars-d-learn mailing list