是否可以将 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;
}
当我 尝试编译这个 时,我得到以下编译错误:
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
constexpr ,但这似乎没有帮助。
原文由 Cory Kramer 发布,翻译遵循 CC BY-SA 4.0 许可协议
如果 lambda 没有捕获,则只能将其转换为函数指针,从 草案 C++11 标准 部分
5.1.2
[expr.prim.lambda] 说( _强调我的_):请注意,cppreference 在其关于 Lambda 函数 的部分中也对此进行了介绍。
因此,以下替代方案将起作用:
这也是这样:
并且正如 5gon12eder 指出的那样,您也可以使用
std::function
,但请注意std::function
是重量级的,所以这不是一个低成本的权衡。