我尝试通过使用 std::cref 将方法作为参数函数传递,该函数本身采用参数,但不知何故我无法正确处理。怎么了?
struct node
{
void get(int &i){
i = x;
}
int x, z;
void foo(std::function<void(int&)>t){
t(z);
}
void bar(){
x = 7;
z = 10;
foo(std::bind(&node::get, this, std::cref(_1)));
cout<< "z:" << z << std::endl; //Here is expected that z is changed to 7
}
};
最佳答案
std::bind
只能将占位符直接作为参数处理:std::bind(…, _1, …)
。
std::cref(_1)
将占位符包装在 std::reference_wrapper
中。 bind
不再将其识别为占位符,并尝试将其直接传递给绑定(bind)函数,就像处理任何其他非占位符参数一样。
要解决此问题以及 bind
的其他限制,请使用 lambda:
foo([this](int &x){return get(std::ref(x));});
我在这里用 ref
替换了 cref
,因为 get()
需要一个非常量引用。你不能在这里使用 cref
,有或没有 lambda。 (请注意,std::ref(x)
等同于此处的 x
,仅用于演示目的而不是 x
。)
关于c++ - std::bind 不会接受绑定(bind)占位符的 std::cref - 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58895056/