原型:
template< class R, class F, class... Args >
bind( F&& f, Args&&... args );
bind函数模板的作用是:
The function template bind
generates a forwarding call wrapper for f
. Calling this wrapper is equivalent to invoking f
with some of its arguments bound to args
.
不怎么好翻译,尝试解释一下:我们为某个函数做一个bind,然后调用该bind和调用函数是一样的,跟函数指针有点像。
#include <random>
#include <iostream>
#include <memory>
#include <functional> void f(int n1, int n2, int n3, const int& n4, int n5)
{
std::cout << n1 << ' ' << n2 << ' ' << n3 << ' ' << n4 << ' ' << n5 << '\n';
} int g(int n1)
{
return n1;
} struct Foo {
void print_sum(int n1, int n2)
{
std::cout << n1+n2 << '\n';
}
int data = ;
}; int main()
{
using namespace std::placeholders; // for _1, _2, _3... // demonstrates argument reordering and pass-by-reference
int n = ;
// (_1 and _2 are from std::placeholders, and represent future
// arguments that will be passed to f1)
auto f1 = std::bind(f, _2, _1, , std::cref(n), n);
n = ;
f1(, , ); // 1 is bound by _1, 2 is bound by _2, 1001 is unused // nested bind subexpressions share the placeholders
auto f2 = std::bind(f, _3, std::bind(g, _3), _3, , );
f2(, , ); // bind to a member function
Foo foo;
auto f3 = std::bind(&Foo::print_sum, &foo, , _1);
f3(); // bind to member data
auto f4 = std::bind(&Foo::data, _1);
std::cout << f4(foo) << '\n';