c++ std::function

测试代码:

cpp 复制代码
#include <iostream>
#include <functional>

int addFunc(int a, int b) {
	return a + b;
}

void testFunction() {
	// 声明一个function,接受俩个int参数,返回int数据
	std::function<int(int, int)> func;

	// 绑定不同的可调用对象

	// 普通函数
	func = addFunc;
	cout << "9526 + 1 :" << func(9526, 1) << endl;

	// lambda表达式
	func = [](int a, int b) { return a - b;};
	cout << "9528 - 1 :" << func(9528, 1) << endl;

	// 成员函数
	class Calculator {
	public:
		int sub(int a, int b) { return a - b; }

		static int staticFuncAdd(int a, int b) { return a + b; }
	};
	Calculator calc;
	// 绑定对象和成员函数
	func = std::bind(&Calculator::sub, &calc, std::placeholders::_1, std::placeholders::_2);
	cout << "0 - 1 = " << func(0, 1) << endl;

	// 绑定静态成员函数
	func = &Calculator::staticFuncAdd;
	cout << "1 + 1 = " << func(1, 1) << endl;

	//仿函数
	class Divider {
	public:
		int operator()(int a, int b) {
			return a / b;
		}
	};
	Divider div;
	func = div;
	cout << "10 / 3 = " << func(10, 3) << endl;
}

打印:

ok

相关推荐
坐吃山猪2 小时前
SpringBoot01-配置文件
java·开发语言
晚风(●•σ )2 小时前
C++语言程序设计——06 字符串
开发语言·c++
我叫汪枫3 小时前
《Java餐厅的待客之道:BIO, NIO, AIO三种服务模式的进化》
java·开发语言·nio
Nicole-----3 小时前
Python - Union联合类型注解
开发语言·python
晚云与城3 小时前
今日分享:C++ -- list 容器
开发语言·c++
兰雪簪轩3 小时前
分布式通信平台测试报告
开发语言·网络·c++·网络协议·测试报告
FPGAI4 小时前
Qt编程之信号与槽
开发语言·qt
Swift社区4 小时前
从 JDK 1.8 切换到 JDK 21 时遇到 NoProviderFoundException 该如何解决?
java·开发语言
0wioiw05 小时前
Go基础(④指针)
开发语言·后端·golang
How_doyou_do6 小时前
数据传输优化-异步不阻塞处理增强首屏体验
开发语言·前端·javascript