Variadic function not recognizing static array length

Ali Çehreli acehreli at yahoo.com
Tue Mar 12 16:35:27 PDT 2013


On 03/12/2013 04:10 PM, Zach the Mystic wrote:
 > On Tuesday, 12 March 2013 at 21:47:02 UTC, Zach the Mystic wrote:
 >> void func(string[2] a) {}
 >>
 >> void func2(T...)(T args) {
 >> static assert(is(typeof(args[0]) == string[2]));
 >> }
 >>
 >> void func3(T...)(T args) {
 >> static assert(args[0].length == 2);
 >> }
 >>
 >> func(["",""]); // Okay
 >> func2(["",""]); // Error: (is(string[] == string[2LU])) is false
 >> func3(["",""]); // Error: _param_0 cannot be read at compile time
 >>
 >> Is this the intended design? Is there a workaround which allows me to
 >> ensure that the parameter is exactly 2 length?
 >
 > I'm just going to assert at runtime instead of at compile time.
 > assert(args[0].length == 2);
 >
 > That's a good workaround, only a minor inconvenience it can't be caught
 > at compile time.

Actually, this is not about variadic function templates. The type of an 
array literal is a slice:

     static assert(is(typeof(["",""]) == string[]));

This doesn't help you but it is possible to cast:

     static assert(is(typeof(cast(string[2])["",""]) == string[2]));

or use a variable with an explicit type:

     string[2] var = ["", ""];
     static assert(is(typeof(var) == string[2]));

Ali



More information about the Digitalmars-d-learn mailing list