首页 > 解决方案 > 如何在 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?

谢谢你的时间。

标签: c++11c++14

解决方案


你倒过来了。_K占位符定义了从K传递给生成的函子(的结果)的第 th 个参数到bind绑定函数的参数中占位符位置的映射。因此,放入_3第一个参数位置bind意味着给绑定函数的第一个参数将是给生成函数的第三个参数。

其他情况有效,因为您的反转逻辑恰好与正确版本相同。


推荐阅读