Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

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.
}
like image 561
user888270 Avatar asked Jun 03 '16 06:06

user888270


People also ask

What does std :: bind do in C++?

std::bind is for partial function application. That is, suppose you have a function object f which takes 3 arguments: f(a,b,c); You want a new function object which only takes two arguments, defined as: g(a,b) := f(a, 4, b);

How does STD bind work?

Internally, std::bind() detects that a pointer to a member function is passed and most likely turns it into a callable objects, e.g., by use std::mem_fn() with its first argument.

What is boost bind?

boost::bind is a generalization of the standard functions std::bind1st and std::bind2nd. It supports arbitrary function objects, functions, function pointers, and member function pointers, and is able to bind any argument to a specific value or route input arguments into arbitrary positions.


1 Answers

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.

like image 135
Holt Avatar answered Oct 10 '22 23:10

Holt