编译时无法读取变量 i

Variable i cannot be read at compile time

我有这个代码:

class Set(T){
    private T[] values;

    T get(uint i){
        return ((i < values.length) ? T[i] : null);
    }
...

当我尝试以这种方式使用 class 时:

set.Set!(int) A;

编译器在 return 行给出错误:set.d|9|error: variable i cannot be read at compile time

有人可以解释一下,我的代码有什么问题吗?谢谢

这就是答案:代码只是引用了错误的变量。它给出错误的原因是 T[i] 试图从编译时类型列表中获取索引......这也需要 i 在编译时可用。但是,由于 i 是一个常规变量,所以它不是。 (顺便说一句,你可以有编译时变量——一个函数的结果可能是 CT 评估的,或者是静态列表上 foreach 的索引,或者是一个枚举值。)但是,这里需要的是数组的运行时索引。 .. 所以值是正确的符号,因为它是数据而不是类型。

亚当·D·鲁佩