I have the following:
void print_str(std::shared_ptr<std::string> str) {
std::cout << str->c_str() << std::endl;
}
int main() {
auto str = std::make_shared<std::string>("Hello");
std::function<void()> f = std::bind(print_str, str);
f(); // correctly print: Hello
return 0;
}
I think the type of std::bind(print_str, str)
is std::function<void(std::shared_ptr<std::string>)>
, but the code above is correctly running. Is there any trick in std::bind
?
env: centos, gcc82
3
Answers
What std::bind does is correct. It uses the value you provided (str) for the call to print_str. So you don’t need to specify it anymore and will always be replaced by the bound value.
output:
f1
binds no values but placeholders and returns anint(int, int)
like functionf2
binds one value and one placeholder and returns anint(int)
like functionf3
binds two values and no placeholder and returns anint()
like functionf4
is likef2
except that the place holder is now the first parameter instead of the second one.Your code falls into the
f3
case.No, the type of
std::bind(print_str, str)
is an unspecified functor type, something likeNote that this is callable with any arguments or none.
What you are experiencing here is correct and is precisely doing what
std::bind
was designed for.Simply speaking:
It turns a function taking
n
parameters into a function takingm
parameters (wheren >= m
).In your particular case, you give it a function taking one parameter and get back a function taking zero parameters. This new function will internally call
print_str
and always passstr
as argument.Side note:
Since there are lambdas in C++11,
std::bind
is sort of redundant.What you are doing is exactly equivalent to this:
This hopefully also helps understanding what
std::bind
does behind the scenes.