本文介绍了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吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 13:09