为什么在使用 std::max 和 c++/CLI 时不能编译?

发布于 2024-09-28 14:23:25 字数 762 浏览 4 评论 0原文

谁能解释一下为什么以下内容可以编译

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?

不能编译?它给出的错误是错误C2665:'std :: max':7个重载中没有一个可以转换所有参数类型

变量aAssigmments的类型为array< ;List^>^fInstanceData->NumRequiredEmpsPerJob 的类型为 array^

std:: 的手册max 声明它通过引用获取值,因此显然在第一个示例中隐式执行此操作,那么为什么编译器不能对 count 属性返回的整数值执行相同的操作,如第二个示例中那样?我可以显式获取对 int 的引用吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦萦几度 2024-10-05 14:23:25

(int)(aAssignments[i]->Count) 将调用属性 getter。但它的计算结果是一个临时变量(右值),它不能绑定到非常量引用。

根据我关于 std::max 的文档,参数应该是 const 引用,并且一切都应该有效。

如果显式指定模板类型参数,例如

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

max(a + 0, b + 0) 怎么样?

(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) ?

冷默言语 2024-10-05 14:23:25

List<>.Count 不是字段,而是属性。您无法创建对托管属性的非托管引用,获取属性值需要调用属性访问器。与第一种方法相比,这里更好的捕鼠器是使用 Math::Max()。

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().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文