On Friday, November 25, 2016 15:59:48 Igor Shirkalin via Digitalmars-d-learn wrote: > On Friday, 25 November 2016 at 14:51:52 UTC, Jonathan M Davis > > auto arr = staticArray!ubyte([1, 2, 3, 4]); > > > > doesn't compile either. The most straightforward > > implementations are something like > > Why? Is it since [1, 2, 3, 4] is int[4] by default?
It's because [1, 2, 3, 4] is inferred to be int[], and _then_ the compiler tries to instantiate the templated function, whereas with ubyte[4] = [1, 2, 3, 4]; the compiler looks at is one thing and determines that the array literal can be ubyte[], and it works. And if staticArray is a variadic template instead of taking an array literal, e.g. auto arr = staticArray!ubyte(1, 2, 3, 4); then the values all get inferred to be int, and when it tries to assign the arguments to the ubyte[4], it doesn't compile, because they're int and not ubyte, which then means that you're forced to either cast the elements to ubyte at the call site auto arr = staticArray!ubyte(cast(ubyte)1, cast(ubyte)2, cast(ubyte)3, cast(ubyte)4); or staticArray itself has to do the cast, but if staticArray itself does the cast, then something like auto arr = staticArray!ubyte(1, 2, 900); would compile without error, and you'd end up with whatever cast(ubyte)900 is. I'd _like_ to be able to find a way to make it so that the semantics of the staticArray function are identical to ubyte[4] = [1, 2, 3, 4]; except that the length is inferred, and I'm coming to the conclusion that it's not possible. That being the case, I'm leaning towards going with T[n] staticArray(T, size_t n)(auto ref T[n] arr) { return arr; } and opening an enhancement request to make the compiler smart enough that auto arr = staticArray!ubyte([1, 2, 3, 4]); would work. I don't see auto arr = staticArray!ubyte(1, 2, 3, 4); ever working unless the symbols being passed in could be examined at compile time, and I don't think that they can be - just their types. - Jonathan M Davis