Lambda表达式可以降级到C ++ 98吗

编程入门 行业动态 更新时间:2024-10-19 23:50:07
本文介绍了Lambda表达式可以降级到C ++ 98吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我最近遇到了一个问题,需要将用lambda表达式编写的C ++ 11代码集成到仅支持C ++ 98编译器的旧代码库中。我想出了lambda的两个等效项,例如Macro,函子或函数指针。但是当用捕获翻译lambda时,它们似乎都受到限制。例如,一个带有回调的简单通用函数:

I recently got a problem need to integrate C++ 11 code written with lambda expression to old code base which only support C++ 98 compiler. I figured out couple of possible equivalences of lambda like Macro, functor or function pointer. But seems they are all limited when translating lambda with capture. For example a simple generic function with call back:

template <class Fn> void ForEachObject(Fn fn) { for (uint i = 0; i < objectCount; i++) { fn(i, address + i * objectSize); } }

,典型的呼叫者会执行以下操作:

and the typical caller will do something like:

uint attributes = 0x0030; .... ForEachObject([=](uint index, void * objectAddress) { if ((ObjectInfo(index) & attributes) != 0) { fn(index, objectAddress); } });

注意这里的属性来自lambda的范围。无论如何,仍然有没有lambda的每个逻辑仍可以重用?还是我必须在每个此类调用方上重新编写逻辑?

Note attributes here is come from out of the scope of lambda. Is there anyway to still reuse the for each logic without lambda? Or I must re-write the logic on every such caller?

推荐答案

使用Functor:

struct Functor { explicit Functor(uint attributes) : attributes(attributes) {} void operator () (uint index, void * objectAddress) const { if ((ObjectInfo(index) & attributes) != 0) { fn(index, objectAddress); } } uint attributes; };

然后致电

uint attributes = 0x0030; // .... ForEachObject(Functor(attributes));

对于每个不同的lambda,您都必须编写一个函子。 您不必修改 ForEachObject

For each different lambda, you have to write a functor. You don't have to modify ForEachObject

更多推荐

Lambda表达式可以降级到C ++ 98吗

本文发布于:2023-11-08 07:36:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1568747.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表达式   Lambda

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!