Mixin programming foreach
eXodiquas
exodiquas at gmail.com
Mon Sep 27 16:59:16 UTC 2021
On Monday, 27 September 2021 at 16:49:15 UTC, Dga123 wrote:
> 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.
I see, thank you very much for the quick answer.
So the "macro magic" does not happen in `template`, it happens in
the `mixin` call, now I understand.
But my last question still stands, how do I build functions that
can work with those vectors because the type of those vectors is
created at compile time.
But I can start working on the problem now. Thanks again for
helping me out here. :)
Have a great day aswell,
eXodiquas
More information about the Digitalmars-d-learn
mailing list