获取指向lambda的函数指针? [英] Obtaining function pointer to lambda?

查看:148
本文介绍了获取指向lambda的函数指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够获得指向C ++中的lambda的函数指针。

I want to be able to obtain a function pointer to a lambda in C++.

我可以做到:

int (*c)(int) = [](int i) { return i; };

当然,以下内容也可以工作-即使它没有创建函数指针。

And, of course, the following works - even if it's not creating a function pointer.

auto a = [](int i) { return i; };

但是以下内容:

auto *b = [](int i) { return i; };

给出GCC中的此错误:

Gives this error in GCC:

main.cpp: In function 'int main()':
main.cpp:13:37: error: unable to deduce 'auto*' from '<lambda closure object>main()::<lambda(int)>{}'
     auto *b = [](int i) { return i; };
                                      ^
main.cpp:13:37: note:   mismatched types 'auto*' and 'main()::<lambda(int)>'

似乎可以将lambda毫无问题地转换为函数指针,但是编译器无法推断函数类型并为其创建指针使用 auto * 。特别是当它可以将唯一的lambda类型隐式转换为函数指针时:

It seems arbitrary that a lambda can be converted to a function pointer without issue, but the compiler cannot infer the function type and create a pointer to it using auto *. Especially when it can implicitly convert a unique, lambda type to a function pointer:

int (*g)(int) = a;

我已经在http://coliru.stacked-crooked.com/a/2cbd62c8179dc61b ,其中包含上述示例。在C ++ 11和C ++ 14下,此行为是相同的。

I've create a little test bed at http://coliru.stacked-crooked.com/a/2cbd62c8179dc61b that contains the above examples. This behavior is the same under C++11 and C++14.

推荐答案

此操作失败:

auto *b = [](int i) { return i; };

因为lambda不是指针。 自动不允许进行转化。即使lambda 可以转换为指针的东西,也不会为您完成-您必须自己做。是否使用强制转换:

because the lambda is not a pointer. auto does not allow for conversions. Even though the lambda is convertible to something that is a pointer, that's not going to be done for you - you have to do it yourself. Whether with a cast:

auto *c = static_cast<int(*)(int)>([](int i){return i;});

或与某些法术

auto *d = +[](int i) { return i; };

这篇关于获取指向lambda的函数指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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