c++11 - 如何在 std::bind 中使用占位符
问题描述
我给你一个简单的代码片段:
#include <functional>
#include <iostream>
using namespace std;
void module2(int x, int y)
{
cout << "\n " << __PRETTY_FUNCTION__ << ":\t x = " << x << "\t y = " << y;
}
void module3(int x, int y, int z)
{
cout << "\n " << __PRETTY_FUNCTION__ << ":\t x = " << x << "\t y = " << y << "\t z = " << z;
}
int main()
{
using namespace std::placeholders;
int a = 39;
int b = 7;
int c = 3;
auto func_m2 = bind(&module2, _1, _2);
func_m2(a, b); // OK
auto func_m2_PH = bind(&module2, _2, _1);
func_m2_PH(b, a); // OK
//---------------------------------------------------------
auto func_m3 = bind(&module3, a, b, c);
func_m3(); // OK
cout << "\n With PlaceHolders:";
auto func_m3_PH_0 = bind(&module3, _1, _2, _3);
func_m3_PH_0(a, b, c); // OK
auto func_m3_PH_1 = bind(&module3, _2, _1, _3);
func_m3_PH_1(b, a, c); // OK
auto func_m3_PH_2 = bind(&module3, _3, _1, _2);
func_m3_PH_2(c, a, b); // KO !!!
auto func_m3_PH_3 = bind(&module3, _3, _2, _1);
func_m3_PH_3(c, b, a); // OK
auto func_m3_PH_4 = bind(&module3, _1, _3, _2);
func_m3_PH_4(a, c, b); // OK
auto func_m3_PH_5 = bind(&module3, _2, _3, _1);
func_m3_PH_5(b, c, a); // KO !!!
return 0;
}
当第一个参数是一个接受 2 个参数的函数时,一切都很好:代码按我的预期工作。
但是,当第一个 std::bind 的参数是具有 3 个(或更多)参数的函数时,代码会按我的预期停止工作(这些情况用 'KO !!!' 标记)
但是,我对 std::bind 及其占位符有什么期望?
在这种特殊情况下,我期望输出:
无效模块3(int,int,int):x = 39 y = 7 z = 3
每次我调用从
bind(&module3, etc...)
但是,更一般地说:
我希望替换名为“_K”的占位符的参数将是传递给底层函数的第 K 个参数(即 std::bind 的第一个参数)。
怎么了?我对std::bind的理解还是这个函数模板有bug?
谢谢你的时间。
解决方案
你倒过来了。_K
占位符定义了从K
传递给生成的函子(的结果)的第 th 个参数到bind
绑定函数的参数中占位符位置的映射。因此,放入_3
第一个参数位置bind
意味着给绑定函数的第一个参数将是给生成函数的第三个参数。
其他情况有效,因为您的反转逻辑恰好与正确版本相同。
推荐阅读
- css - Laravel Mix 将所有 vue 组件 css 提取到单个 app.css
- c++ - std::stoul 不抛出 std::out_of_range
- esp8266 - 无法使用 nodemcu 在 16x2 显示器(I2C 板)上显示任何内容?
- python - 如何在 Python 中更改联系表的颜色饱和度?
- html - Bootstrap 4 标志在桌面上的位置中心
- c# - .net core 和 IIS 安装和配置的 Inno Setup
- scala - 我的 Maven 项目配置错误是什么?不选择依赖项或类结构
- javascript - ReactJS 中的基石工具 - 不处理第一个加载位之后工作
- javascript - 超链接并显示选项卡
- javascript - 如何将自定义指令绑定到所有输入元素?