如何在带有捕获的函数中传递lambda
How to pass a lambda in a function with a capture?
我的标题是我的主要问题。下面的代码显示了我想要做的事情,但它导致了一个错误。
class B
{
public:
void DoSomething(void (*func)())
{
func();
}
};
class A
{
public:
int x;
void Start(B* b)
{
auto func = [this]()->void
{
this->x++;
};
b->DoSomething(func);
}
};
如果我删除了"this"关键字,那么程序就可以工作了,但我不能引用x变量。
那么我该如何做到这一点呢?
更改
void DoSomething( void (*func)() )
至
void DoSomething( std::function<void()> func )
您当前的参数类型void (*func)()
是函数指针,这是一种不保持状态的可调用类型(可以像函数一样调用)。这就是为什么不能将变量this
传递到函数中的原因。
只有不捕获任何内容的lambda才能转换为无状态函数指针
然而,std::function
可以表示(几乎)任何可调用的东西。它可以是一个原始函数,或者是实现operator()
的类的实例,也可以是您的lambda持有状态。
另一种选择是简单地使用模板来避免与需要由std::function打包的大型lambda相关的潜在开销。
#include <functional>
using namespace std;
template<typename Callable>
void DoSomething(Callable c) { c(); } // calls the lambda with no args
int main()
{
DoSomething([]{ printf("Hellon"); });
DoSomething([msg = "World"] { printf("%sn", msg); });
}
Live代码:http://goo.gl/LMvm3a
相关文章:
- 可组合的lambda/std::函数与std::可选
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 如何建立使用模板函数的lambda函数的尾部返回类型
- 如何将lambda作为模板类的成员函数参数
- 我可以将调用类的"this"传递给 lambda 函数吗?
- 模板函数指针和lambda
- 两组使用lambda函数的大括号
- 尝试将lambda函数放在队列中时出现一般分配器错误(可能是与unique_ptr有关的错误)
- 我可以在这里替换什么,因为我不能在 C# 中使用隐式变量的 lambda 函数?
- 在构造函数中使用 lambda 的 C++ 类
- 如何调用存储在指向"std::函数"的指针中的 lambda?
- 为什么我不能在 constexpr lambda 函数中使用 std::tuple
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- C++:Lambda 函数指针转换的用例是什么?
- 将有状态的 lambda 传递到 C 样式函数中,而无需上下文参数
- std::映射服装比较函数和函数/lambda错误
- 在可移动类型的构造函数 lambda 中捕获此内容的安全使用
- 排序测试模板化函数 lambda:非法使用此类型作为表达式
- 将匿名函数(lambda)保存为函数类型变量
- 如何编写将自身作为回调传递的匿名函数/lambda