是否可以将lambda函数作为函数指针传递?如果是这样,我必须做错了,因为我收到编译错误.
请考虑以下示例
using DecisionFn = bool(*)();
class Decide
{
public:
Decide(DecisionFn dec) : _dec{dec} {}
private:
DecisionFn _dec;
};
int main()
{
int x = 5;
Decide greaterThanThree{ [x](){ return x > 3; } };
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我尝试编译它时,我得到以下编译错误:
In function 'int main()':
17:31: error: the value of 'x' is not usable in a constant expression
16:9: note: 'int x' is not const
17:53: error: no matching function for call to 'Decide::Decide(<brace-enclosed initializer list>)'
17:53: note: candidates are: …Run Code Online (Sandbox Code Playgroud) 调用指向不再存在的 lambda 的指针是否合法?
这是演示代码片段。
#include <iostream>
typedef int (*Func)(int a);
int main()
{
Func fun;
{
auto lambda = [](int a)->int{std::cout << a << std::endl; return a;};
fun =lambda;
}
fun(6); //Is it legal? The variable lambda does not exist anymore.
}
Run Code Online (Sandbox Code Playgroud)
通用条件怎么样,比如说有捕获的 lambda?