直接看代碼,代碼說明一切
#include <functional>
#include <iostream>
using namespace std;
class Test
{
public:
double test(int a, int b)
{
cout << "a = " << a << " b = " << b << endl;
return 0;
}
};
double globalTest(int a, int b)
{
cout << "a = " << a << " b = " << b << endl;
return 0;
}
int main(void)
{
// 最普通的用法,直接綁定全局函數(shù)
{
// <> 里的返回值和參數(shù)需要 和 要綁定的函數(shù)參數(shù)和返回值對應(yīng)上
std::function<double(int, int)> f = &globalTest;
f(2, 3);
// 輸出 a = 2 b = 3
}
Test t;
// 綁定成員函數(shù)
{
std::function<double(Test & obj,int, int)> f = &Test::test;
t.test(1, 2);
// obj 是調(diào)用這個(gè)函數(shù)的對象,這里用t.text,那么obj就是t的引用
// 輸出 a = 1 b = 2
}
{
std::function<double()> f = std::bind(&Test::test, &t, 2, 3);
//f(9, 10); // err 編譯錯(cuò)誤, 函數(shù)接收的參數(shù)是根據(jù) double() 括號中的參數(shù)決定的
f(); // ok 函數(shù)接收到的值是 9
// 輸出 a = 2 b = 3
}
{
std::function<double(int)> f = std::bind(&Test::test, &t, 5, 6);
//f(); // err 編譯錯(cuò)誤 參數(shù)匹配不上
f(3); // 編譯成果,但是 3 被拋棄了,函數(shù)接受到的值是 9和10
// 輸出 a = 5 b = 6
}
//std::placeholders::_1 占位符
{
std::function<double(int)> f = std::bind(&Test::test, &t, std::placeholders::_1, 15);
f(2); //函數(shù)接收到的值是 2 15
//f(2, 10); // err 參數(shù)匹配不上 f只接受一個(gè)參數(shù)
// 輸出 a = 2 b = 15
}
{
std::function<double(int, int)> f= std::bind(&Test::test, &t, std::placeholders::_1, std::placeholders::_1);
f(9, 15); // 函數(shù)接收到的值是 9, 9
// std::placeholders::_1 占位符接收到的值都是9
// 輸出 a = 9 b = 9
}
{
std::function<double(int, int)> f= std::bind(&Test::test, &t, std::placeholders::_2, std::placeholders::_1);
f(9, 15); // 函數(shù)接收到的值是 15, 9
// std::placeholders::_1 占位符接收到的值是 15
// std::placeholders::_2 占位符接收到的值是 9
// 輸出 a = 15 b = 9
}
return 0;
}