【发布时间】:2020-03-12 16:06:33
【问题描述】:
我尝试通过使用 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
}
};
【问题讨论】:
-
Lambda 意味着没有真正的理由需要在新代码中使用
std::bind()... -
@HolyBlackCat 指出问题在于
std::cref的使用;您显然可以使用_1。但我会让 HolyBlackCat 自己写答案。 -
std::cref创建了一个对const T的引用,但get()引用了一个非常量int,所以你为什么期望这种绑定能够编译,甚至像这样包装_1占位符是否合法?
标签: c++ function c++11 methods bind