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