std :: bind将不接受绑定占位符的std :: cref-为什么?

时间:2019-11-16 20:46:32

标签: c++ function c++11 methods bind

我尝试通过使用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
    }
};

1 个答案:

答案 0 :(得分:3)

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。)