d - Templated Multi-Dimensional Arrays -
i'm trying experiment templates , tried implement templated arrays, can declared like:
array!(float, 3, 2, 1) myarray;
i've browsed through several implementations of problem in c++ can't seem convert d have little experience language (with d).
anyways these stuff tried, unfortunately none of them worked:
1. compile-time functions - generate code of format
"datatype[d0][d1]...[dn] identifier"
import std.conv; static string generatearray(d...)(string type, string identifier, d dimensions) { string result = type; for(int = 0; < dimensions.length; i++) { result ~= "[" ~ to!(string)(dimensions[i]) ~ "]"; } result ~= " " ~ identifier ~ ";"; return result; } int main(string[] args) { enum deb = generatearray("float", "data", 3, 2, 1); pragma(msg, deb); return 0; }
which can wrap simple array class
class array(t, d...) { mixin(generatearray(t, "data", d)); }
but code fails with:
./template_recursion.d(10): error: variable cannot read @ compile time ./template_recursion.d(18): error: template instance template_recursion.expandtuple!(int, int, int) error instantiating ./template_recursion.d(18): error: ctfe failed because of previous errors in expandtuple
2. recursive templates - stated earlier have seen implementations of in c++, can't seem transform statements d compiler accepts.
template<class t, unsigned ... restd> struct array; template<class t, unsigned primaryd > struct array<t, primaryd> { typedef t type[primaryd]; type data; t& operator[](unsigned i) { return data[i]; } }; template<class t, unsigned primaryd, unsigned ... restd > struct array<t, primaryd, restd...> { typedef typename array<t, restd...>::type onedimensiondownarrayt; typedef onedimensiondownarrayt type[primaryd]; type data; onedimensiondownarrayt& operator[](unsigned i) { return data[i]; } };
first code, using mixins:
dimensions
aliasseq
(aka typetuple
, misnomer because 1 contains integers), can indexed values known @ compile time, runtime loop doesn't supply.
you can, however, use compile-time foreach loop, such:
foreach(auto dimension; dimensions) { result ~= "[" ~ to!(string)(dimensions[i]) ~ "]"; }
second code, using templates:
template multiarray(basetype, dimentions...) { static if(dimensions.length == 0) alias multiarray = basetype; else alias multiarray = multiarray!(basetype[dimensions[0]], dimensions[1..$]; }
Comments
Post a Comment