是否可以将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矢量,但失败了:
auto ignore = [&]() { return 10; }; //1
std::vector<decltype(ignore)> v; //2
v.push_back([&]() { return 100; }); //3
Run Code Online (Sandbox Code Playgroud)
错误:没有匹配函数来调用'std :: vector <main():: <lambda()>> :: push_back(main():: <lambda()>)'
我不想要一个函数指针向量或函数对象向量.但是,封装真实 lambda表达式的函数对象向量对我有用.这可能吗?