std::function + std::bind,可以将所有函数都能统一到 std::function。
在应用中,可以优雅的将类成员函数使用到诸如回调,线程函数等场合。
举例:
#include <thread>
#include <functional>
using std::placeholders::_1;
using std::placeholders::_2;
class Test
{
// ...
public:
int add(const int a, const int b)
{
return a+b;
}
}
//
int main()
{
Test t;
std::function< int(int, int) > pfun = std::bind(&Test::add, &t, _1, _2);
//auto pfun = std::bind(&Test::add, &t, _1, _2);
// 直接调用
pfun(2, 3);
// 用于线程函数
std::thread t(pfun, 4, 6);
return 0;
}