且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将lambda表达式转换为函数指针

更新时间:2023-11-11 12:18:22

本身没有语法,它是隐式转换。只需将其强制转换(显式或隐式),即可获得函数指针。但是,此问题在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.