是否可以将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) 我不喜欢在我的代码中散布着魔术盒......这两个类究竟是如何工作的,基本上允许任何函数映射到一个函数对象,即使函数<>有一个完全不同的参数设置为一个im传递给 boost::bind
它甚至适用于不同的调用约定(即成员方法__thiscall在VC下,但"普通"函数通常__cdecl或者__stdcall需要与C兼容的那些).
看一下下面列出的代码示例,我使用编译器资源管理器(使用 gcc 和 clang)对其进行了测试,它可以工作并打印出 200 的(预期)输出。
我想弄清楚的是:为什么这个 C++ 是有效的。或者不是吗?
在这里,我使用关键字为 function typeusing定义别名(而不是 a ) ,它描述了采用 an作为参数并返回 an (是函数类型,而不是函数指针类型!)的函数。等效语法是. 由于 C++ 标准规定,每个函数都有一个使用该语法的等效形式,因此很明显,这是指定此函数类型的明确定义的方法。typedefftintintfttypedeftypedef int ft(int);typedefusingusing ft = int(int)
现在有趣的部分来了:我使用类型ft来指定另一个函数 () 的参数类型print_it,然后调用它,传递一个 lambda 函数。我的问题是:C++ 标准在哪里/如何说这实际上应该起作用?我认为这是传递 lambda 的一种非常简单的方法。我不清楚这是否有效,因为 lambda 实际上是一个函子,而不是严格意义上的函数。所以我认为尚不清楚这个 lambda 是否与类型匹配ft,因此可以传递给print_it(如果ft被定义为是的话std::function<int(int)>,那就很清楚了)。
代码示例:
#include <iostream>
using ft = int(int);
void print_it (ft f, int a)
{
std::cout << f(a) << …Run Code Online (Sandbox Code Playgroud)