gpt4 book ai didi

c++ - 将捕获lambda作为函数指针传递

转载 作者:行者123 更新时间:2023-12-03 07:03:46 25 4
gpt4 key购买 nike

是否可以将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;
}

当我 try to compile this时,出现以下编译错误:

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常量,但这似乎无济于事。

最佳答案

draft C++11 standard5.1.2 [expr.prim.lambda]说(强调我的意思),如果lambda无法捕获,则只能将其转换为函数指针:

The closure type for a lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function having the same parameter and return types as the closure type’s function call operator. The value returned by this conversion function shall be the address of a function that, when invoked, has the same effect as invoking the closure type’s function call operator.



注意,cppreference在 Lambda functions的部分中也对此进行了介绍。

因此,以下替代方法将起作用:
typedef bool(*DecisionFn)(int);

Decide greaterThanThree{ []( int x ){ return x > 3; } };

这样:
typedef bool(*DecisionFn)();

Decide greaterThanThree{ [](){ return true ; } };

并且正如 5gon12eder所指出的,您也可以使用 std::function ,但是请注意 std::function is heavy weight,因此这不是一种低成本的折衷方案。

关于c++ - 将捕获lambda作为函数指针传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62537642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com