Filling a Tuple-like struct in variadic member

RivenTheMage riven-mage at id.ru
Tue Nov 8 03:21:41 PST 2011


Is it possible to do such thing without using string mixin?

------------
import std.stdio;
import std.metastrings;

struct Key(T...)
{
	static string declareFields() // compile-time
	{
		string declaration;

	        foreach (index, type; T)
			declaration = declaration ~ Format!("%s field_%s;\n", type.stringof, index);

	        return declaration;
	}

	mixin(declareFields());
	uint numFields;

	static string declareFieldsAssignment() // compile-time
	{
		string declaration;
		immutable(string) exceptionMessage = "Argument type mismatch.";

	        foreach (index, type; T)
		{
			declaration = declaration ~
				Format!("if (_arguments[%s] != typeid(%s))\n", index, type.stringof) ~
	        	        	"        throw new Exception(\"" ~ exceptionMessage ~
"\");\n" ~
					"else\n" ~
					"{\n" ~
				Format!("	field_%s = *(cast(%s*) _argptr);\n", index, type.stringof) ~
				Format!("	_argptr += field_%s.sizeof;\n", index) ~
					"}\n\n";
		}

		return declaration;
	}

	void assignFields(...)
	{
		mixin(declareFieldsAssignment());
		numFields = _arguments.length;
	}
}

void main()
{
	Key!(string) testval;

	testval.assignFields("test string");
	writeln(testval);
}


More information about the Digitalmars-d-learn mailing list