struct A{
int[3] _data;
ref int opIndex(size_t i) { return _data[i]; }
int opIndex(size_t i) const{ return _data[i]; }
}
T fun(T)(const ref T a){
T ai = a;
swap(ai[0], ai[1]); // error
return ai;
}
immutable A a = A();
immutable A b = fun(a);
void main(){ }上面的代码给出了以下错误:
Error: ai.opIndex(0LU) is not an lvalue
Error: ai.opIndex(1LU) is not an lvalue
called from here: fun(a)ai是a的副本,它是一个左值,所以我不明白为什么我会得到这个错误。
发布于 2012-02-01 02:56:08
您需要使用opIndexAssign而不是opIndex进行赋值,因此请使用int opIndexAssign(int value, size_t i)而不是ref int opIndex(size_t i)。
你可以在这里找到更多:Operator Overloading
编辑:
import std.algorithm;
struct A{
int[3] _data;
ref int opIndex(size_t i) { return _data[i]; }
}
T fun(T)(){
T ai;
// swap(ai._data[0], ai._data[1]);
swap(ai[0], ai[1]);
return ai;
}
immutable A a = A();
immutable A b = fun!(A);
void main(){ }https://stackoverflow.com/questions/9085146
复制相似问题