相关疑难解决方法(0)

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

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

c++ lambda function-pointers c++11

186
推荐指数
4
解决办法
12万
查看次数

调用指向超出范围的 lambda 的指针是否合法?

调用指向不再存在的 lambda 的指针是否合法?

这是演示代码片段

#include <iostream>

typedef int (*Func)(int a);

int main()
{
 Func fun;

 {
    auto lambda = [](int a)->int{std::cout << a << std::endl; return a;};   
    fun =lambda;
 }

 fun(6); //Is it legal? The variable lambda does not exist anymore.
}
Run Code Online (Sandbox Code Playgroud)

通用条件怎么样,比如说有捕获的 lambda?

c++ lambda c++11

6
推荐指数
1
解决办法
121
查看次数

标签 统计

c++ ×2

c++11 ×2

lambda ×2

function-pointers ×1