问题描述
是否可以将lambda函数作为函数指针传递?
Is it possible to pass a lambda function as a function pointer? If so, I must be doing something incorrectly because I am getting a compile error.
考虑下面的例子
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;
}
当我,我得到以下编译错误:
When I try to compile this, I get the following compilation error:
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:
9:5: note: Decide::Decide(DecisionFn)
9:5: note: no known conversion for argument 1 from 'main()::<lambda()>' to 'DecisionFn {aka bool (*)()}'
6:7: note: constexpr Decide::Decide(const Decide&)
6:7: note: no known conversion for argument 1 from 'main()::<lambda()>' to 'const Decide&'
6:7: note: constexpr Decide::Decide(Decide&&)
6:7: note: no known conversion for argument 1 from 'main()::<lambda()>' to 'Decide&&'
一个错误消息来消化,但我想我得到的是,lambda不能被视为一个 constexpr
所以我不能把它作为一个函数指针?我尝试了 x
const,但是这似乎没有帮助。
That's one heck of an error message to digest, but I think what I'm getting out of it is that the lambda cannot be treated as a constexpr
so therefore I cannot pass it as a function pointer? I've tried making x
const as well, but that doesn't seem to help.
推荐答案
一个lambda只能转换为一个函数指针,如果它不捕获,从部分 5.1.2
[expr.prim.lambda] (强调我):
A lambda can only be converted to a function pointer if it does not capture, from the draft C++11 standard section 5.1.2
[expr.prim.lambda] says (emphasis mine):
请注意,cppreference还介绍了。
Note, cppreference also covers this in their section on Lambda functions .
因此,以下替代方法可用:
So the following alternatives would work:
typedef bool(*DecisionFn)(int);
Decide greaterThanThree{ []( int x ){ return x > 3; } };
因此:
typedef bool(*DecisionFn)();
Decide greaterThanThree{ [](){ return true ; } };
和指出,您也可以使用,但请注意,so it is not a cost-less trade-off。
and as 5gon12eder points out, you can also use std::function, but note that std::function is heavy weight, so it is not a cost-less trade-off.
这篇关于传递lambda作为函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!