昨晩、これと同じことがC++で出来るかどうか質問を受けた。5という数字が与えられたときに、0,1,2,2,3,3,3,4,4,4,4,5,5,5,5,5という数列をコンパイル時に生成できるかという問題である。
本の虫: C++0xによるコンパイル時の配列生成
を読んで,D言語だったら(上記の問題とは異なる問題であるものの)表題の型を計算することが「普通に」簡単にできるよなーって思った.
import std.conv; string array(int dim) { string s; foreach (i; 0..dim) { foreach (_; 0..i+1) { s ~= "[" ~ to!string(i+1) ~ "]"; } } return s; } template Cycle(T, int n) { mixin("alias " ~ T.stringof ~ array(n) ~ " Cycle;"); } void main() { Cycle!(int, 0) a; static assert(is(typeof(a) == int)); Cycle!(int, 1) b; static assert(is(typeof(b) == int[1])); Cycle!(int, 2) c; static assert(is(typeof(c) == int[1][2][2])); Cycle!(int, 3) d; static assert(is(typeof(d) == int[1][2][2][3][3][3])); }
あれ? to!string って前からコンパイル時に実行可能だったっけ?