数组中的额外逗号

Arl*_*len 5 d

void main(){    
  int[3] arr = [1, 2, 3,];    
}
Run Code Online (Sandbox Code Playgroud)

额外的逗号是合法的还是因为编译器错误而没有被标记为错误?我有很多mixins生成带有额外逗号的数组.我想知道我是否应该花时间删除它们.

即使这个编译没有错误:

void main(){    
  int[3] arr = [1, 2, 3,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,];    
}
Run Code Online (Sandbox Code Playgroud)

Meh*_*dad 7

我认为允许模板(甚至mixins)以通用方式工作是合法的:

template Foo(T) { }                       //What if Foo is empty like this?

auto arr = [1, 2, Foo!(int), Foo!(long)];
//         [1, 2, , ]
Run Code Online (Sandbox Code Playgroud)

它使模板容易使用,因此您不必特殊情况下对特殊输出.

一个更现实的例子:

template Iota(size_t start, size_t end)  //All integers in range [start, end)
{
    static if (start < end)
        alias TypeTuple!(start, Iota!(start + 1, end)) Iota;
    else
        alias TypeTuple!() Iota;
}

auto arr1 = [-10, Iota!(0, 3)];    // arr is now [-10, 0, 1, 2]
auto arr2 = [-10, Iota!(a, b)];    // arr is now [-10, a .. b]
Run Code Online (Sandbox Code Playgroud)

现在如果a等于b?会发生什么?然后arr2衰败到[-10, ].

  • 我认为这个答案几乎无关紧要,因为IIRC这里提到的所有情况(除了字符串mixins)都被扩展为数据结构,而不是文本:即逗号只与解析器相关,而不是模板扩展代码. (3认同)