当存储在std :: function中时,无法捕获的lambda无法转换为函数指针

当存储在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(+[](){});
//     ^