Captureless lambda cannot be converted to function pointer when stored in std::function

我只是一个虾纸丫 提交于 2020-01-21 01:14:29

问题


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.

Tested on VC13 and GCC 5.3 / 5.2.0 / 4.8

Minimal testing example:

#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);
}

expected output would be

1
<address>
1
<address>

actual output

0
0
1
<address>

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


回答1:


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()).

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

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


来源:https://stackoverflow.com/questions/34768791/captureless-lambda-cannot-be-converted-to-function-pointer-when-stored-in-stdf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!