4 ms·
I think that mixins - both template mixins that essentially copy/paste declarations (including functions) and the mixin statement that takes a string to be comp
by badsectoracula 5y ago
I think that mixins - both template mixins that essentially copy/paste declarations (including functions) and the mixin statement that takes a string to be compiled as source code - can be as weird to follow as macros in C.
Contrived example:
import std.stdio;
mixin template Func(string s, string r)
{
mixin("string " ~ s ~ "()" ~
"{" ~
"return \"" ~ r ~ "\";" ~
"}");
}
mixin template Comb(string name, char c=',')
{
mixin(function string(){
import std.conv;
string r;
enum counter(size_t x=[__traits(allMembers, mixin(__MODULE__))].length)=x;
string suffix = to!string(counter!());
r ~= "mixin Func!(\"Foo" ~ suffix ~ "\", \"Hello\");";
r ~= "mixin Func!(\"Bar" ~ suffix ~ "\", \"World\");";
r ~= "string " ~ name ~ "() {";
r ~= "return Foo" ~ suffix ~ "() ~ \"" ~ c ~ " \" ~ Bar" ~ suffix ~ "();";
r ~= "}";
return r;
}());
}
void main()
{
mixin Comb!("Mixer");
writeln(Mixer());
}
It is just that the language has more features than C so they aren't needed as often. But in my eyes at least the mixin statement is basically C macros on steroids :-P.