简体   繁体   中英

how to pass a std::bind object to a function

I need to pass a bind function to another function but i am getting error that there is no conversion available-

cannot convert argument 2 from 'std::_Bind<true,std::string,std::string (__cdecl *const )(std::string,std::string),std::string &,std::_Ph<2> &>' to 'std::function<std::string (std::string)> &'

The function:

std::string keyFormatter(std::string sKeyFormat, std::string skey)
{
    boost::replace_all(sKeyFormat, "$ID$", skey);
    return sKeyFormat;
}

The usage is like -

auto fun = std::bind(&keyFormatter, sKeyFormat, std::placeholders::_2);
client(sTopic, fun);

The client function looks like-

void client(std::function<std::string(std::string)> keyConverter)
{
    // do something.
}

You are using the wrong placeholders , you need _1 :

auto fun = std::bind(&keyFormatter, sKeyFormat, std::placeholders::_1);

The number of the placeholder is not here to match the position of the args, but rather to choose which arguments to send to the original function in which position:

void f (int, int);

auto f1 = std::bind(&f, 1, std::placeholders::_1);
f1(2); // call f(1, 2);
auto f2 = std::bind(&f, std::placeholders::_2, std::placeholders::_1);
f2(3, 4); // call f(4, 3);
auto f3 = std::bind(&f, std::placeholders::_2, 4);
f3(2, 5); // call f(5, 4);

See std::bind , especially the examples at the end.

Your client function looks like it's incomplete. You probably want the following:

void client(const std::string &, std::function<std::string(std::string)> keyConverter);

Also, the placeholder should be std::placeholders::_1 .

A complete example would be:

#include <iostream>
#include <functional>
#include <string>

std::string keyFormatter(std::string sKeyFormat, std::string skey) {
    return sKeyFormat;
}

void client(std::string, std::function<std::string(std::string)> keyConverter) {
    // do something.
}


int main() {
    auto sKeyFormat = std::string("test");
    auto sTopic = std::string("test");
    auto fun = std::bind(&keyFormatter, sKeyFormat, std::placeholders::_1);
    client(sTopic, fun);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM