Can Lambda expression be downgraded to C++ 98

若如初见. 提交于 2019-12-20 02:57:38

问题


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);
    }
});

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?


回答1:


With 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;
};

And then call

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

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




回答2:


Can Lamda expression be downgrade to C++ 98

No they cannot. Prior C++11 standards have no notion of lambda syntax.

Though there are surrogates available like boost::lambda

You can provide functor style classes, overriding the call operator (<return_type> operator()(<args>);), to provide the same effect, as mentioned in the other answer.



来源:https://stackoverflow.com/questions/33506531/can-lambda-expression-be-downgraded-to-c-98

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!