在c++11中重新绑定lambda.有可能吗
Rebinding lambda in c++11... is it possible?
我有一种情况,我有一个lambda作为由某个函数调用创建的成员变量。问题是,它将此作为其操作的一部分。稍后,我希望能够复制整个对象。。。
然而,在复制时,我不知道lambda是如何创建的(它可能是通过不同的代码路径在几个位置定义的)。因此,对于在复制构造函数中放入什么,我有些不知所措。理想情况下,我希望将lambda的捕获"重新绑定"到创建的新"this"。
这有可能吗?
以下是一些示例代码:
#include <iostream>
#include <string>
#include <functional>
class Foo
{
public:
Foo () = default;
~Foo () = default;
void set (const std::string & v)
{
value = v;
}
void set ()
{
lambda = [&]()
{
return this->value;
};
}
std::string get ()
{
return lambda();
}
std::string value;
std::function <std::string (void)> lambda;
};
int main ()
{
Foo foo;
foo.set ();
foo.set ("first");
std::cerr << foo.get () << std::endl; // prints "first"
foo.set ("captures change");
std::cerr << foo.get () << std::endl; // prints "captures change"
Foo foo2 (foo);
foo2.set ("second");
std::cerr << foo.get () << std::endl; // prints "captures change" (as desired)
std::cerr << foo2.get () << std::endl; // prints "captures change" (I would want "second" here)
return 0;
}
提前谢谢。
您看到的问题是this
指针被捕获到lambda中,但您现在正在从另一个对象执行函数的副本。它在您的示例中起作用,因为这两个对象都存在,但它只是一个等待发生的悬挂指针。
要做到这一点,最干净的方法是修改std::function
和Lambda,使其采用指向类的指针的参数,并使用传入的指针而不是捕获它。根据lambda的内容,可以选择捕获值。
class Foo
{
public:
Foo () = default;
~Foo () = default;
void set (const std::string & v)
{
value = v;
}
void set ()
{
lambda = [](Foo* self)
{
return self->value;
};
}
std::string get ()
{
return lambda(this);
}
std::string value;
std::function <std::string (Foo*)> lambda;
};
IDEOne 的示例
我认为您不能修改闭包。如果您需要函数对另一个对象进行操作,则需要将指向该对象的指针作为函数的参数:
class Foo
{
public:
Foo () = default;
~Foo () = default;
void set (const std::string & v)
{
value = v;
}
void set ()
{
lambda = [](Foo* t)
{
return t->value;
};
}
std::string get ()
{
return lambda(this);
}
std::string value;
std::function <std::string (Foo*)> lambda;
};
相关文章:
- 传递给 lambda C++绑定函数
- 获取具有静态局部变量的绑定/推断捕获 lambda 的函数指针
- 在 c++ 中绑定 lambda
- 结构化绑定语法是否可以在多态 lambda 中使用
- 重构嵌套绑定以使用 lambda 函数
- 解除 lambda 事件处理程序的绑定
- std::绑定到 lambda: 编译错误
- 使用带有增强兽的 lambda 而不是绑定
- 是否可以将匿名 lambda 函数绑定到对象以允许 lambda 中的代码访问对象的成员?
- 为什么 lambda 表达式的捕获列表无法使用结构化绑定分解
- std :: async使用绑定到lambda的rvalue引用
- 在c++11中重新绑定lambda.有可能吗
- C++将此指针与 lambda 函数中的绑定一起使用
- Lambda 表达式"无法绑定"
- MSVC和boost::lambda::绑定错误:T0:不允许使用标准参数
- boost绑定或返回常量的lambda函数
- 从绑定到lambda函数中获取运算符()的类型
- c++14用于函数绑定的可变lambda捕获
- std::bind():将lambda与右值引用作为参数绑定
- 是否可以绑定lambda函数的第二个参数