定义f函数拥有5个int形参,使用bind函数绑定f函数,代码如下:
#include#include //bind函数在functional头文件中 #include using namespace std; int f(int a, int b, int x, int c, int y); // 声明函数 bool isShorter(char &s1, char &s2) { return s1 > s2; } int main() { string str = "Hello World"; std::cout << str << std::endl; // 想要向控制台输出12345 auto g = std::bind(f, 1, 2, std::placeholders::_2, 4, std::placeholders::_1); g(3, 5); // 根据g(3,5)的第一个实参与占位符_1绑定,第二个实参5与占位符_2绑定 string words("3254617"); sort(words.begin(), words.end(), isShorter); cout << words << endl; string words2("3254617"); sort(words2.begin(), words2.end(), std::bind(isShorter, std::placeholders::_2, std::placeholders::_1)); cout << words2 << endl; } int f(int a, int b, int x, int c, int y) { cout << a << b << x << c << y << endl; return 0; }
执行 g(3,5) ,发现输出如下:
得出结论:传递给g的参数按位置绑定到占位符,即,第一个参数绑定到_1,第二个参数绑定到_2。



