Static arrays, typeof and IFTI?
Norbert Nemec
Norbert at Nemec-online.de
Sun Oct 9 23:42:26 PDT 2011
Hi there,
after a very busy and eventful year in my personal life, I have now
finally found some time to play with D2. I am very impressed by the
progress!
One thing I noticed was that static arrays are somehow strangely limited:
It is possible to overload based on the length:
--------
void f(int[3] x) {
writeln("int[3]: ",x);
}
void f(int[4] x) {
writeln("int[4]: ",x);
}
int main(string argv[]) {
f([1,2,3]);
f([1,2,3,4]);
return 0;
}
--------
However, used as function template argument, a static array is casted to
a dynamic array:
-----------
void g(T)(T x) {
static assert (__traits(isStaticArray,T));
enum N = T.init.length;
writeln(N,": ",x);
}
int main(string argv[]) {
g([1,2,3]);
return 0;
}
------------
gives the error message:
| Error: static assert (__traits(isStaticArray,int[])) is false
| instantiated from here: g!(int[])
Without the assertion, N is defined to 0.
Further investigation shows:
-------
g!(int[3])([1,2,3]); // passes a static array
-------
int[3] x3 = [1,2,3];
g(x3); // passes a static array
-------
auto z3 = [1,2,3]; // defines z3 as dynamic array
g(y3); // passes a dynamic array
-------
So it seems, the problem is that array literals on their own turned into
dynamic arrays unless you explicitly state a static array type in some way.
Wouldn't it make more sense the other way around? After all, turning a
static array into a dynamic array is easy, the other way around is
prohibited by the compiler. If array literals simply had a static array
type, they could be implicitly casted to dynamic arrays when necessary
but stay static if possible.
Greetings,
Norbert
More information about the Digitalmars-d
mailing list