首页 > 解决方案 > std::bind 不接受绑定占位符的 std::cref - 为什么?

问题描述

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

标签: c++functionc++11methodsbind

解决方案


std::bind只能将占位符直接作为参数处理:std::bind(…, _1, …).

std::cref(_1)将占位符包装在std::reference_wrapper. bind不再将其识别为占位符,并尝试将其直接传递给绑定函数,就像处理任何其他非占位符参数一样。

要解决 的此限制和其他限制bind,请使用 lambda:

foo([this](int &x){return get(std::ref(x));});

我已替换crefref此处,因为get()需要非常量引用。cref无论有没有 lambda,你都不能在这里使用。(请注意,这与此处std::ref(x)等效,仅用于演示目的。)xx


推荐阅读