关于std::function
程序员文章站
2022-06-15 12:06:22
...
主要用于函数回调,通过std::function
对C++中各种可调用实体(普通函数、Lambda表达式、函数指针、以及其它函数对象等)的封装,形成一个新的可调用的std::function
对象;让我们不再纠结那么多的可调用实体。一切变的简单粗暴。
示例代码:
#include <functional>
#include <iostream>
std::function<void(int)> Functional;
// 普通函数
void OnImageGrabbedFunc(int a)
{
std::cout << "OnImageGrabbedFunc: " << a << std::endl;
}
// 仿函数
class ImageGrabbedFunction
{
public:
ImageGrabbedFunction(int id) : m_id(id)
{
}
void operator()(int a)
{
std::cout << "ImageGrabbedFunction" << m_id <<": " << a << std::endl;
}
private:
int m_id;
};
// Lambda表达式
auto lambda = [](int a)->void{ std::cout << "lambda: " << a << std::endl;};
// 1.类成员函数
// 2.类静态函数
class FunClass
{
public:
void ClassMember(int a) { std::cout << "ClassMember: " << a << std::endl; }
static void StaticMember(int a) { std::cout << "StaticMember: " << a << std::endl; }
};
void main()
{
Functional = OnImageGrabbedFunc;
Functional(1);
ImageGrabbedFunction fun(0);
Functional = fun;
Functional(2);
Functional = lambda;
Functional(3);
FunClass obj;
Functional = std::bind(&FunClass::ClassMember, obj, std::placeholders::_1);
Functional(4);
Functional = obj.StaticMember;
Functional(5);
}
运行结果: