Creating Tuple or AliasSeq
ANtlord via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Apr 6 22:43:29 PDT 2017
Hello! I've got an issue related to making a Tuple or AliasSeq
using income template arguments. I want to create template makes
an array of objects from array of arrays have different sizes and
different types of values.
I created temporary solution. It is a concatenation of strings
that will be passed to mixin.
But I just want to reorder parameters and pass them to ObjectType
using AliasSeq or Tuple. Does it possible?
import std.stdio;
template objectFactory(ObjectType, Args...)
{
static string loopGen() {
string code = (ObjectType[]).stringof ~ " res = []; ";
foreach(i, _; Args)
{
enum level = to!string(i);
code ~= "foreach(elem" ~ level ~ "; Args[" ~ level ~ "])";
}
code ~= "res ~= " ~ ObjectType.stringof ~ "(";
foreach(i, _; Args)
{
enum level = to!string(i);
code ~= "elem" ~ level;
static if(i + 1 < Args.length)
{
code ~= ", ";
}
}
code ~= ");";
return code;
}
static ObjectType[] factory()
in {
static assert(Args.length > 0);
foreach(argumentCases; Args)
static assert(argumentCases.length > 0);
}
body
{
enum codeString = loopGen();
mixin(codeString);
return res;
}
alias objectFactory = factory;
}
Example:
struct Pair {
int number;
string name;
}
auto pairKit = objectFactory!(Pair, [1], ["qwe", "asd"]);
auto pairSet = pairKit();
assert(pairSet.length == 2);
writeln(pairSet[0]); // writes Pair(1, "qwe");
writeln(pairSet[1]); // writes Pair(1, "asd");
Thanks. Sorry if my english is not clear.
More information about the Digitalmars-d-learn
mailing list