Howdy ho everyone,
I found this forum very helpful for my (maybe) stupid questions, so I give it a try again because I don't understand what's happening here.
First of all, I'm not exactly sure what this code here, from the documentation at https://dlang.org/articles/mixin.html, does:
template GenStruct(string Name, string M1)
{
const char[] GenStruct = "struct " ~ Name ~ "{ int " ~ M1 ~ "; }";
}
mixin(GenStruct!("Foo", "bar"));
In my understanding we create a template called GenStruct
with compile time arguments Name
and M1
. We then create the char[] GenStruct
which holds the source code for the struct
. Afterwards we do the mixin
call and create the source code during compile time to have it ready to go. But I don't understand why the char[] GenStruct
is there. Is this the name of the mixin
or is the template GenStruct
the name of what we pass to the mixin
? Can we create more than one const char[] in one template
scope and what would it do if we could? So I'm a bit confused here.
But nevertheless, I copied the code and changed it a bit to something like this:
template Vector(int dimension) {
string cps = "";
foreach(d; 0..dimension) {
cps ~= "x" ~ d ~ " = 0;\n";
}
const char[] Vector = "struct Vector {\n" ~ dimension.to!string ~ cps ~ "}";
}
In my head a call to mixin(Vector!5)
should result in something like this:
struct Vector5 {
int x0;
int x1;
int x2;
int x3;
int x4;
}
But it does not compile because Error: declaration expected, not foreach
which I understand as "foreach is not possible during compile time", whereas I don't see any problem with compile time availability of anything in this template. Obviously I don't understand something here, so it would be awesome if someone could help me out here. :P
And as a final question. Let's say the above problems are all solved and I construct such a template. How could I build functions that take any of those Vector
s as an argument?
For example I want to add two of those, the function would look something like this, or am I lost again?
Vector!T add(Vector!T lhs, Vector!T rhs) {
return ?;
}
How could I iterate over all components if such a Vector
?
I hope I am not on the completely wrong track to tackle this problem.
Thanks in advance. :)
eXodiquas