why doesn't this compile when using std::max and c++/CLI?

我们两清 提交于 2019-12-22 10:54:04

问题


Can anyone please explain why the following will compile

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

but

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

wont? The error it gives is error C2665: 'std::max' : none of the 7 overloads could convert all the argument types

The variable aAssigmments is of type array<List<int>^>^ and fInstanceData->NumRequiredEmpsPerJob is of type array<int>^

The manual for std::max states that it takes values by reference, so it's clearly doing this implicitly in the first example, so why can't the compiler do the same for integer values returned by the count property, as in the second example? Can I get a reference to an int explicitly?


回答1:


(int)(aAssignments[i]->Count) will call the property getter. But it evaluates to a temporary variable (rvalue) which cannot bind to a non-const reference.

According to my documentation on std::max, the parameters should be const references and everything should work.

What happens if you explicitly specify the template type parameter, e.g.

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

?

What about max<int>(a + 0, b + 0) ?




回答2:


List<>.Count is not a field, it is a property. You can't create a unmanaged reference to a managed property, obtaining the property value requires calling the property accessor. Short from your first approach, the better mousetrap here is to use Math::Max().



来源:https://stackoverflow.com/questions/3986522/why-doesnt-this-compile-when-using-stdmax-and-c-cli

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!