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

std::bind won't accept an std::cref of a bind-placeholder - why?

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

我在这里用 ref 替换了 cref,因为 get() 需要一个非常量引用。你不能在这里使用 cref,有或没有 lambda。 (请注意,std::ref(x) 等同于 x,仅用于演示目的而不是 x。)