我尝试通过使用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::ref(x)
等效于x
,并且仅用于演示目的,而不是x
。)