2010-10-21 46 views
3

誰能請解釋爲什麼下面將編譯爲什麼在使用std :: max和C++/CLI時不編譯?

int a = aAssignments[i]->Count; 
int b = fInstanceData->NumRequiredEmpsPerJob[i]; 
fInstanceData->NumSlotsPerJob[i] = max(a,b); 

fInstanceData->NumSlotsPerJob[i] = max((int)(aAssignments[i]->Count), (int)(fInstanceData->NumRequiredEmpsPerJob[i])); //why on earth does this not work? 

不會?它提供錯誤是error C2665: 'std::max' : none of the 7 overloads could convert all the argument types

可變aAssigmmentsarray<List<int>^>^類型和fInstanceData->NumRequiredEmpsPerJobarray<int>^

std::max手冊說,它以引用的取值類型的,因此它明顯地含蓄地在第一個例子中這樣做,那麼爲什麼編譯器不能對count屬性返回的整數值做同樣的事情?就像第二個例子一樣?我可以明確地獲得對int的引用嗎?

+0

它甚至如何編譯'Count'屬性,數組具有'Length'屬性。 – leppie 2010-10-21 10:40:30

+1

@leppie這是一個列表數組,我將數組索引到'i'並計算該列表的元素。 – 2010-10-21 11:00:05

+0

啊正確:)我錯過了。 – leppie 2010-10-21 11:05:42

回答

2

(int)(aAssignments[i]->Count)將調用屬性獲取器。但它的計算結果是一個不能綁定到非const引用的臨時變量(rvalue)。

根據我的關於std::max的文檔,參數應該是const引用,並且一切都應該工作。

如果您明確指定了模板類型參數(例如,

max<int>((int)(aAssignments[i]->Count), (int)(fInstanceData->NumRequiredEmpsPerJob[i]))

max<int>(a + 0, b + 0)怎麼樣?

+0

如果我明確指定模板類型,它接受第一個參數'aAssignments [i] - > Count''但不是第二個參數,給我一個'不能將參數2從'int'轉換爲'const int&''錯誤。儘管將這個參數加0仍然有效! *但是必須有更好的辦法... * – 2010-10-21 13:29:47

+1

發生了什麼事情是這樣的:第二個參數已經描述了一個int類型的左值,因此編譯器刪除了這個類型(我錯誤地相信了)。由於左值位於託管堆上,因此它可能被GC移動,並且需要託管引用('int%')而不是C++引用('int&')。該值需要被複制到一個臨時的,這不在託管堆上,所以它綁定得很好,並且應該執行該操作。看起來像一個編譯器錯誤。 – 2010-10-21 14:55:18

+0

這是一個編譯器錯誤,也會影響本機C++。將暫時發佈錯誤報告鏈接。 – 2010-10-21 15:06:52

1

列表<> .Count不是字段,它是屬性。您不能創建託管屬性的非託管引用,獲取屬性值需要調用屬性訪問器。從你的第一種方法來看,這裏更好的捕鼠器是使用Math :: Max()。

+0

這是一個真正的編譯器錯誤 – 2010-10-21 15:25:25

相關問題