2012-01-31 107 views
3
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(){ } 

上面的代碼提供了以下錯誤:opIndex的正確實現是什麼?

Error: ai.opIndex(0LU) is not an lvalue 
Error: ai.opIndex(1LU) is not an lvalue 
     called from here: fun(a) 

aia副本,它是一個左值,所以我不明白爲什麼我得到的錯誤。

回答

2

您需要使用opIndexAssign而不是opIndex進行分配,因此而不是ref int opIndex(size_t i)使用int opIndexAssign(int value, 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(){ } 
+0

在哪裏分配? – Arlen 2012-01-31 18:58:09

+0

哦,我明白了,忘了交換。看起來好像你沒有得到實際的錯誤,嘗試取消註釋交換,你會得到一個新的錯誤:'錯誤:靜態變量a不能在編譯時引用',這似乎是實際的問題。此外'T ai = a;'給你一個不可變的結構。 – dav1d 2012-01-31 19:14:35

+0

好的。那麼'T ai = a;'不應該給一個不變的。反正有沒有這樣的表現? – Arlen 2012-01-31 19:32:01

相關問題