digitalmars.D.learn - Filling a Tuple-like struct in variadic member
- RivenTheMage (45/45) Nov 08 2011 Is it possible to do such thing without using string mixin?
- Philippe Sigaud (23/24) Nov 08 2011 Hi,
- RivenTheMage (1/2) Nov 08 2011 Yes, that's the problem.
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);
}
Nov 08 2011
On Tue, Nov 8, 2011 at 12:21, RivenTheMage <riven-mage id.ru> wrote:Is it possible to do such thing without using string mixin?Hi, you can use another tuple: struct Key(T...) { T fields; uint numFields = T.length; void assignFields(U...)(U args) if (U.length == T.length) { foreach(i, field; fields) fields[i] = args[i]; } } void main() { Key!(string, int, int delegate(int)) testval; writeln("Numfields: ", testval.numFields); testval.assignFields("abc", 1, (int i) {return i+1;}); writeln(testval); } You can also test at compile-time if U and T are compatible, before the assignement. Or do you really need assignField to work with runtime values ? Philippe
Nov 08 2011
Or do you really need assignField to work with runtime values ?Yes, that's the problem.
Nov 08 2011








RivenTheMage <riven-mage id.ru>