C# lambda 函数的含义和C++翻译
C# lambda function meaning and C++ translation
我正在尝试从 C# 转换为C++我在 Internet 上找到的图像的过滤函数,以便我可以编译一个 DLL 并在我的项目中使用它。原始 C# 代码为:
Parallel.For(0, height, depthArrayRowIndex => {
for (int depthArrayColumnIndex = 0; depthArrayColumnIndex < width; depthArrayColumnIndex++) {
var depthIndex = depthArrayColumnIndex + (depthArrayRowIndex * width);
.
.
.
... other stuff ...
}
我问题的第一部分是:如何
depthArrayRowIndex => {
工程?depthArrayRowIndex
的含义是什么:
var depthIndex = depthArrayColumnIndex + (depthArrayRowIndex * width);
这是我C++翻译:
concurrency::parallel_for(0, width, [&widthBound, &heightBound, &smoothDepthArray] () {
for (int depthArrayColumnIndex = 0; depthArrayColumnIndex < width; depthArrayColumnIndex++) {
int depthIndex = depthArrayColumnIndex + (depthArrayRowIndex * width);
.
.
.
... other stuff ...
}
但显然depthArrayRowIndex
在这里没有任何意义。如何在C++中翻译工作代码中的 C# 代码?
非常感谢!! :-)
在本例中,"depthArrayRowIndex" 是 lambda 函数的输入参数,因此在C++版本中,您可能需要更改
[&widthBound, &heightBound, &smoothDepthArray] ()
为
[&widthBound, &heightBound, &smoothDepthArray] (int depthArrayRowIndex)
如果您想进一步了解 C# lambda 语法,此链接可能很有用
http://msdn.microsoft.com/en-us/library/vstudio/bb397687.aspx
Foo => {
// code
return bar; // bar is of type Bar
}
与
(Foo) => {
// code
return bar; // bar is of type Bar
}
将其转换为C++
[&](int Foo)->Bar {
// code
return bar; // bar is of type Bar
}
屁股Foo
属于int
型。 在C++中,单行 lambda 可以跳过->Bar
部分。 不返回任何内容的 Lambda 可以->void
跳过。
您可以在C++ lambda 的[]
中列出捕获的参数(以及它们是否由值或引用捕获(,但 C# lambda 相当于捕获智能引用隐式使用的所有内容。 如果 lambda 的生存期限制在创建 lambda C++的范围内,则[&]
是等效的。
如果它可以持续更长时间,您需要处理 lambda 捕获的数据的生命周期管理,并且您需要更加小心并且仅按值捕获(并且可能在捕获shared_ptr
之前将数据打包到shared_ptr
中(。
depthArrayRowIndex
基本上是(并行(外部for循环的索引变量/值。它将从0
包容性变为height
独家:
http://msdn.microsoft.com/en-us/library/dd783539.aspx
一点解释(C#(:并行的整个第三个参数是lambda函数,该操作获取一个Int32参数,它恰好是循环索引。
所以我认为你的C++翻译应该从: concurrency::parallel_for(0, height, ...
而不是width
.
- 不同翻译单元中不可重载的非内联函数定义
- 需要将一行代码从C++ Qt翻译成PyQt
- 为什么未命名的结构内联变量在每个翻译单元中没有相同的地址?
- 在没有 API 的情况下使用谷歌翻译文本
- 如何执行 cppcheck 交叉翻译单元 (CTU) 静态分析?
- 模板变量是否允许在多个翻译单元中并有效合并?
- 是否允许类在程序中的不同翻译单元之间具有不同的定义?
- 我怎样才能代替使用新的使用malloc翻译
- 为什么具有静态存储持续时间的同一内联变量在包含在 VS2017 编译的两个翻译单元中时会构造和销毁两次
- 如何将 'in' 关键字从 python 翻译成 c++?
- 为什么不同的翻译单元没有独立和沙盒的内存空间?
- 如何用c语言翻译openssl命令pbkdf2
- 为什么编译器不在同一翻译单元中警告 ODR 违规
- 静态变量在同一个翻译单元中被静态方法使用时是否保证被初始化?
- 如何翻译这个给定代码中的 ::* 运算符和member_fn?
- 来自不同翻译单元的函数会干扰吗?
- 在 opengl 中翻译相机时遇到问题
- 如何平均继续翻译向量
- 如何在C++中的不同翻译单元之间共享枚举的实例
- 在Visual Studio中更新Qt翻译(.ts文件)时出现未指定错误