当存储在std :: function中时,无法捕获的lambda无法转换为函数指针 [英] Captureless lambda cannot be converted to function pointer when stored in std::function

查看:646
本文介绍了当存储在std :: function中时,无法捕获的lambda无法转换为函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,不需要捕获的C ++ lambda可以转换 到c风格的函数指针。不知何故,使用 std :: function :: target 转换它不工作(即返回一个nullptr),还有 target_type

Usually, a C++ lambda without a capture should be convertable to a c-style function pointer. Somehow, converting it using std::function::target does not work (i.e. returns a nullptr), also the target_type does not match the signature type even though it seems to be the same.

在VC13和GCC 5.3 / 5.2.0 / 4.8上测试

Tested on VC13 and GCC 5.3 / 5.2.0 / 4.8

最小测试示例:

#include <functional>
#include <iostream>

void Maybe() {

}

void callMe(std::function<void()> callback) {
    typedef void (*ftype)();
    std::cout << (callback.target_type() == typeid(ftype)) << std::endl;
    std::cout << callback.target<ftype>() << std::endl;
}

int main() {
    callMe([] () {});
    callMe(Maybe);
}

预期输出为

1
<address>
1
<address>

实际输出

0
0
1
<address>

问题是:为什么lambda的签名与传递的函数不同?

The question is: Why does the lambda's signature differ from the passed function?

推荐答案

在你的第一次调用中, std :: function 指针,它只是存储它,与它的实际类型(这不是 void())。

In your first call, std::function does not bother with decaying the lambda into a pointer, it just stores it, with its actual type (which is indeed not void()).

可以强制lambda在之前通过简单地使用一元来构造 std :: function +

You can force the lambda to decay into a pointer before constructing the std::function with the latter by simply using a unary +:

callMe(+[](){});
//     ^

这篇关于当存储在std :: function中时,无法捕获的lambda无法转换为函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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