Search code examples
d

Variable i cannot be read at compile time


I have this code:

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

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

And when I try use this class this way:

set.Set!(int) A;

compiler gives error at the return line: set.d|9|error: variable i cannot be read at compile time

Can somebody explain, what's wrong in my code? Thanks.


Solution

  • That is the answer: the code simply referenced the wrong variable. The reason it gave the error it did is that T[i] is trying to get an index out of a compile-time list of types... which needs i to be available at compile time too. However, since i is a regular variable, it isn't. (You can have compile time variables btw - the result of a function may be CT evaled, or the index on a foreach over a static list, or an enum value.) However, what was wanted here was a runtime index into the array... so the values is the right symbol since it is the data instead of the type.

    By Adam D. Ruppe