std::function
std::function是一個函數包裝器模闆,最早來自boost庫,對應其boost::function函數包裝器。在c++11中,std::function能包裝任何類型的可調用元素,可以包裝:函數、函數指針、類成員函數指針或任意類型的函數對象。
包裝類成員函數示例
#include <functional>
#include <iostream>
class Publisher
{
public:
void RegistFunc(std::function<void(int, int)> func) {
std::cout << "Publisher RegistFunc()" << std::endl;
func(1, 2);
}
};
class Subscriber
{
public:
Subscriber(int a, int b) : a_(a), b_(b) {}
virtual ~Subscriber(){};
void Notify(int a, int b) {
std::cout << "Notify: a = " << a << ", b = " << b << std::endl;
this->a_ = a;
this->b_ = b;
}
void Start() {
std::cout << "Subscriber Start()" << std::endl;
Publisher pub;
std::function<void(int,int)> func = std::bind(&Subscriber::Notify, this, std::placeholders::_1, std::placeholders::_2);
pub.RegistFunc(func);
}
void show() {
std::cout << "show: a = " << a_ << ", b = " << b_ << std::endl;
}
private:
int a_;
int b_;
};
int main(int argc, char* argv[])
{
std::cout << "main start" << std::endl;
Subscriber sb(5, 6);
sb.show();
sb.Start();
sb.show();
std::cout << "main end" << std::endl;
}
執行結果
main start
show: a = 5, b = 6
Subscriber Start()
Publisher RegistFunc()
Notify: a = 1, b = 2
show: a = 1, b = 2
main end
std::bind時,可以通過占位符,改變參數順序。
//修改為
std::bind(&Subscriber::Notify, this, std::placeholders::_2, std::placeholders::_1);
執行結果
main start
show: a = 5, b = 6
Subscriber Start()
Publisher RegistFunc()
Notify: a = 2, b = 1
show: a = 2, b = 1
main end