使用成员在 class 中创建 lambda 表达式
Creating lambda expression in class using members
我正在尝试创建一个 class 成员函数,其中 returns 一个基于 class 成员的 lambda 表达式。为了简化,我创建了这个示例代码。
#include <functional>
class A
{
private:
int value;
public:
// Default constructor
A()
: value(0)
{ };
// Constructor
A(int value)
: value(value)
{ };
// Returns a lambda expression
std::function<int()> get_value()
{
return [](){ return value; };
// Gives error: "error: 'this' was not captured for this lambda function"
}
};
我知道这个实现可以更容易地编程(去掉 lambda 表达式),但我认为解释和理解这个概念是很好的。
问题:如何在class成员lambda表达式中使用class成员变量?换句话说:如何在 class?
的 lambda 函数中捕获 'this'
如果你想捕获 this
那么你应该捕获 this
:
return [this](){ return value; };
然而,这伴随着通常的警告,即 lambda 捕获的 this
只能在 this
存活时使用。
PS
I know for this implementation it can be programmed much easier (leave away the lambda expression), [...]
如果你想要一个 returns 你是 A
的 value
的可调用函数,那么如果不使用 lambda 表达式,我将不知道如何(轻松地)做到这一点.我宁愿看到你的设计中的问题。如上所述,只要 A
对象还存在,调用者就需要谨慎使用返回的 std::function
。有一个不明显的依赖性,其效果是您的 A
很容易被错误使用:
auto f = A{}.get_value();
这会造成损坏 std::function<int()>
。坦率地说,您的代码就是我所说的 "encapsulation gone terribly wrong"。当然你的代码只是一个例子,但考虑这个例子:
struct A { int value = 0; };
int main() {
A a;
auto f = [&](){ return a.value; };
}
此处调用者(即 A
的用户)在其代码中明确具有依赖性(f
的可用性取决于 a
的生命周期)。
我正在尝试创建一个 class 成员函数,其中 returns 一个基于 class 成员的 lambda 表达式。为了简化,我创建了这个示例代码。
#include <functional>
class A
{
private:
int value;
public:
// Default constructor
A()
: value(0)
{ };
// Constructor
A(int value)
: value(value)
{ };
// Returns a lambda expression
std::function<int()> get_value()
{
return [](){ return value; };
// Gives error: "error: 'this' was not captured for this lambda function"
}
};
我知道这个实现可以更容易地编程(去掉 lambda 表达式),但我认为解释和理解这个概念是很好的。
问题:如何在class成员lambda表达式中使用class成员变量?换句话说:如何在 class?
的 lambda 函数中捕获 'this'如果你想捕获 this
那么你应该捕获 this
:
return [this](){ return value; };
然而,这伴随着通常的警告,即 lambda 捕获的 this
只能在 this
存活时使用。
PS
I know for this implementation it can be programmed much easier (leave away the lambda expression), [...]
如果你想要一个 returns 你是 A
的 value
的可调用函数,那么如果不使用 lambda 表达式,我将不知道如何(轻松地)做到这一点.我宁愿看到你的设计中的问题。如上所述,只要 A
对象还存在,调用者就需要谨慎使用返回的 std::function
。有一个不明显的依赖性,其效果是您的 A
很容易被错误使用:
auto f = A{}.get_value();
这会造成损坏 std::function<int()>
。坦率地说,您的代码就是我所说的 "encapsulation gone terribly wrong"。当然你的代码只是一个例子,但考虑这个例子:
struct A { int value = 0; };
int main() {
A a;
auto f = [&](){ return a.value; };
}
此处调用者(即 A
的用户)在其代码中明确具有依赖性(f
的可用性取决于 a
的生命周期)。