有以下技巧.因为无法推导
长度,因此不理想,但这成功地把alloca
注入到调用者域
中.
cpp
import core.stdc.stdlib:alloca;
import std.range:ElementType;
import core.lifetime:moveEmplace;
struct VLA(T,alias len){
T[] storage;
this(R)(R initializer,return void[] storage=alloca(len*T.sizeof)[0..len*T.sizeof]){
this.storage=cast(T[])storage;
foreach(ref element;this.storage){
assert(!initializer.empty);
auto init=initializer.front;
moveEmplace!T(init,element);
initializer.popFront();
}
}
ref T opIndex(size_t i)return{ return storage[i]; }
T[] opSlice()return{ return storage; }
}
auto vla(alias len,R)(R initializer,void[] storage=alloca(len*ElementType!R.sizeof)[0..len*ElementType!R.sizeof]){
return VLA!(ElementType!R,len)(initializer,storage);
}
void main(){
import std.stdio,std.string,std.conv,std.range;
int x=readln.strip.to!int;
writeln(vla!x(2.repeat(x))[]);
}