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

问题描述 投票:0回答:1

我尝试通过使用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++ function c++11 methods bind
1个回答
2
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.