module pind.samples.ja.templates_more.templates_more_9; import std.string; string structDefinition(string name, Members...)() { /* メンバーはペアで指定する: まず型、 * その次に名前。 */ static assert((Members.length % 2) == 0, "Members must be specified as pairs."); /* 構造体定義の最初の部分。 */ string result = "struct " ~ name ~ "\n{\n"; foreach (i, arg; Members) { static if (i % 2) { /* 奇数番号の引数はメンバーの名前である * 必要がある。ここでは名前を扱う代わりに、 * 以下の'else'節でMembers[i+1]として * 使用する。 * * 少なくとも、メンバー名が * 文字列として指定されていることを確認する。 */ static assert(is (typeof(arg) == string), "Member name " ~ arg.stringof ~ " is not a string."); } else { /* この場合、'arg'は * メンバーの型である。それが実際に型であることを確認する。 */ static assert(is (arg), arg.stringof ~ " is not a type."); /* 型とその名前からメンバー定義を * 生成する。 * * 注釈: 以下のMembers[i]の代わりに * 'arg'と記述することもできる。 */ result ~= format(" %s %s;\n", Members[i].stringof, Members[i+1]); } } /* 構造体定義の閉じ括弧。 */ result ~= "}"; return result; } import std.stdio; void main() { writeln(structDefinition!("Student", string, "name", int, "id", int[], "grades")()); }