C++ std::function 泛化函数对象

std::function 是 C++11 标准库中的一个类模板,用于封装可调用对象(函数、函数指针、成员函数指针、Lambda 表达式等),并提供一种统一的方式来管理它们。

通过 std::function,你可以将可调用对象存储在一个对象中,并稍后调用它们,而无需在编译时知道确切的类型。这使得 std::function 特别适合于实现回调函数、事件处理等场景。

简言之:function 提供了一种灵活的方式来存储和调用可调用对象,可以在运行时确定要调用的对象。

#if 1
#include <iostream>
#include <functional>
using namespace std;

struct Functor
{
	int operator()(int a, int b)
	{
		return a + b;
	}
};

void my_add(double a, double b)
{
	cout << a + b << endl;
}

struct MyClass
{
	int my_function(int a, int b)
	{
		return a + b;
	}
};

void test()
{
	// 1. 封装函数对象
	function<int(int, int)> func1 = Functor();
	cout << func1(10, 20) << endl;

	// 2. 封装普通函数
	function<void(double, double)> func2 = my_add;
	func2(3.14, 3.15);

	// 3. 封装匿名函数
	function<void(void)> func3 = []() {
		cout << "hello world" << endl;
	};
	func3();

	// 4. 封装成员函数
	MyClass mc;
	auto my_function = bind(&MyClass::my_function, &mc, placeholders::_1, placeholders::_2);
	function<int(int, int)> func4 = my_function;
	cout << func4(100, 200) << endl;
}


int main()
{
	test();
	return 0;
}


#endif
未经允许不得转载:一亩三分地 » C++ std::function 泛化函数对象
评论 (0)

4 + 8 =