D 言語の最も変態的で最も強力な機能がこれでしょう.
ソースコードをまさにコンパイル時に生成する.
str_mixin.d
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import std.stdio;
class X{
mixin( MakeAttribute!(int, "number").value ); // == int number;
mixin( MakeAttribute!(string, "text").value ); // == string number;
}
template MakeAttribute(T, string name){
immutable value = T.stringof ~ " " ~ name ~ ";";
}
void main(){
mixin("int a = 100;");
writeln(a);
mixin("int b = 200;");
writeln(b);
auto x = new X;
x.number = 20;
x.text = "hoge";
writeln(x.number);
writeln(x.text);
}
|
str_mixin.d の実行結果は:
[cactus:~/code_d/d_tuts]% ./str_mixin
100
200
20
hoge