How to pass an std :: bind object to an object

I need to pass a binding function to another function, but I get an error that there is no conversion -

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)> &'

Function:

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

Use -

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

Client function looks like

void client(std::function<std::string(std::string)> keyConverter)
{
    // do something.
}
+4
source share
2 answers

You are using the wrong one placeholders, you need to _1:

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

The placeholder number here does not match the args position, but rather chooses 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.

+7
source

Your client function appears to be incomplete. You probably want the following:

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

In addition, placeholder should be std::placeholders::_1.

Full example:

#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);
}
+1
source

All Articles