我尝试将方法作为参数函数传递,该方法本身通过使用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
的此限制和其他限制,请使用lambda:
foo([this](int &x){return get(std::ref(x));});
我在这里用
cref
替换了ref
,因为get()
需要一个非常量引用。无论有没有lambda,您都不能在此处使用cref
。
尝试不使用std::bind
。虽然不建议弃用-当然不建议使用。改用lambda: