vendredi 5 juillet 2019

How to use placeholders in std::bind

I give you a simple snippet of code:

#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;
}

When the first argument is a function that takes 2 arguments everything is fine: the code works as I expect.

However when the first std::bind's parameter is a function with 3 (or more) arguments the code stops working as I expect (these cases are marked with 'KO !!!' )

But, what do I expect from std::bind and its placeholders?

In this particular case I expect the output:

void module3(int, int, int): x = 39 y = 7 z = 3

every time that I invoke the function object generated from

bind(&module3, etc...)  

but, more in general:
I expect that the parameter that replaces the placeholder named '_K' will be the K-th parameter passed to the underlying function (i.e. the first parameter of the std::bind).

What is wrong? My understanding of the std::bind or there is a bug in this function template?

Thanks for your time.

Aucun commentaire:

Enregistrer un commentaire