c++ - 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
}
};
解决方案
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()
需要非常量引用。cref
无论有没有 lambda,你都不能在这里使用。(请注意,这与此处std::ref(x)
等效,仅用于演示目的。)x
x
推荐阅读
- c - 当我向函数添加更多参数时,为什么我的内核会崩溃?
- flutter - Flutter:我尝试使用 dio pack 和 http 从后端获取带有授权不记名令牌的 api,我得到了异常但正在邮递员中工作
- javascript - 如何在不打开电子邮件应用程序的情况下从锚标签中抓取电子邮件 ID
- php - PHP 和 OCI8 在连接时生成 HTTPd 分段错误(不是每次)
- reactjs - 使用 Link 导航时,具有 next-redux-wrapper 状态的 Next.js 被重置为初始值
- c# - 从 C# 中的 url 字符串中获取数字部分
- java - Minecraft Bukkit - 右键单击村民时的自定义 GUI
- javascript - 更改添加代码后jquery优惠券字段不起作用
- delphi - Delphi - 亚马逊 MWS API - 如何从 SHA 256 HMAC 派生 Base64 HMAC?
- php - 在多个相似目录中执行 bash