将lambda表达式转换为函数指针 [英] Conversion of lambda expression to function pointer

查看:546
本文介绍了将lambda表达式转换为函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是此问题的后续问题: Lambda我如何作为参数传递

This is a follow up question to this question: Lambda how can I pass as a parameter

MSDN应该已经将该项目标记为固定。我看了一下规范,但在将其规范转换为语法时遇到了麻烦。

MSDN supposedly has marked the item as fixed. I took a look at the specifications, but I'm having trouble converting their specifications into what the syntax should be.

因此,例如:

void printOut(int(*eval)(int))
{
    for(int x = 0; x < 4; ++x)
    {
        std::cout << eval(x) << std::endl;
    }
}

现在说我有lambda:

Now say I have the lambda:

auto lambda1 = [](int x)->int{return x;};

lambda1 转换为的语法是什么等价的函数指针,以便可以将其传递给 printOut

What is the syntax to convert lambda1 into the functional pointer equivalent so it can be passed to printOut?

此外,实际上包含某些内容的lambda呢?括号?例如:

Also, what about lambdas which actually have something in the brackets? For example:

int y = 5;
auto lambda2 = [y](void)->int{return y;};

如果无法将这种lambda转换为函数指针,是否有替代方法将这种类型的lambda表达式传递给 printOut (甚至是 printOut 的修改版本,如果是的话)是什么?

If this kind of lambda can't be converted to a function pointer, is there an alternative method for passing this type of lambda expression to printOut (or even a modified version of printOut, if so what's the syntax)?

推荐答案

本身没有语法,它是隐式转换。只需将其强制转换(显式或隐式),即可获得函数指针。但是,此问题在Visual Studio 2010发布后已修复,因此不存在。

There is no syntax per se, it's an implicit conversion. Simply cast it (explicitly or implicitly) and you'll get your function pointer. However, this was fixed after Visual Studio 2010 was released, so is not present.

您不能像您指出的那样,将捕获完全的lambda变成函数指针,因此必须更改函数 printOut 。您可以对函数本身进行概括:

You cannot make a capture-full lambda into a function pointer ever, as you noted, so it's the function printOut that'll have to change. You can either generalize the function itself:

// anything callable
template <typename Func>
void printOut(Func eval) 
{
    // ...
}

或特别泛化函数类型:

// any function-like thing that fits the int(int) requirement
void printOut(std::function<int(int)> eval) 
{
    // ...
}

每个人都有自己的取舍。

Each has their own trade-off.

†据我所知,我们将它打包在Service Pack中还是未知,或者是否需要等到新版本发布。

†As far as I know, it's unknown of we'll get it in a service pack, or if we need to wait until a new release.

这篇关于将lambda表达式转换为函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆