Mixin programming foreach
Dga123
Dga123 at 123.fi
Mon Sep 27 16:49:15 UTC 2021
On Monday, 27 September 2021 at 16:23:50 UTC, eXodiquas wrote:
> 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.
> [...]
> But nevertheless, I copied the code and changed it a bit to
> something like this:
>
> ```d
> template Vector(int dimension) {
> string cps = "";
> foreach(d; 0..dimension) {
> cps ~= "x" ~ d ~ " = 0;\n";
make a `string cps(){}` function. TemplateDeclaration can only
contains DeclDefs,
i.e declarations and no expressions.
b.t.w `template Vector` can also be a string `Vector(int
dimension){}` function.
So finally to obtain something like this
```d
import std;
string vector(int dimension) {
string cps;
foreach(d; 0..dimension) {
cps ~= "int x" ~ d.to!string ~ " = 0;\n";
}
return "struct Vector" ~ dimension.to!string ~" {\n" ~ cps ~
"}";
}
mixin(vector(5));
```
function used in mixin are evaluated at compile time and are
generally more perfomantly evaluated than eponymous template
(that contains a single member
named as the template). Also less constraint on what can be done.
Have a great day,
Dga.
More information about the Digitalmars-d-learn
mailing list