lambda表达式作为函数的入参时如果直接这么写会报错
#include <iostream>
#include <algorithm>
using namespace std;
void fun( void (*f)() )
{
f();
}
int main()
{
int num=10;
fun(
[=]()
{
int b;
b=num;
}
);
return 0;
}
内容为
error: cannot convert ‘main()::<lambda()>’ to ‘void ()()’ for argument ‘1’ to 'void fun(void ()())’|
这时候需要用到std::function模板类,做以下改动就可以 了
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;
void fun( std::function<void()>f )
{
f();
}
int main()
{
int num=10;
fun(
[=]()
{
int b;
b=num;
}
);
return 0;
}
本文探讨了C++中lambda表达式与std::function模板类的使用技巧,解决将lambda表达式作为函数参数时遇到的类型转换错误,通过实例演示如何正确地使用std::function来接受lambda表达式。
1449

被折叠的 条评论
为什么被折叠?



