如何在C ++中使用std :: ref和std :: bind

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

我尝试将方法作为参数函数传递,该方法本身通过使用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
2个回答
1
投票

[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


0
投票

尝试不使用std::bind。虽然不建议弃用-当然不建议使用。改用lambda:

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