我最近遇到了一个问题,需要将用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吗
发布评论