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

相关推荐
C++ 老炮儿的技术栈3 小时前
基于Qt实现轻量化本地音乐播放器
开发语言·c++·qt·c·播放器·音乐
qq_448011163 小时前
C语言中的柔性数组
c语言·开发语言·柔性数组
小白学大数据3 小时前
长周期爬虫的数据一致性:断点续爬 + 事务回滚保障采集质量
开发语言·爬虫·测试工具
zlinear数据采集卡4 小时前
D223上位机C#开发实战:从帧解析到波形显示的完整实现
开发语言·arm开发·嵌入式硬件·fpga开发·开源·c#
Poo_Chai4 小时前
QT emit信号后完整处理流程,包括槽函数响应流程
java·开发语言·数据库
瑞码空间4 小时前
Java 图形界面(GUI)完整知识点手册
java·开发语言·图形界面·swing
小努蛋5 小时前
linux编译openresty异常问题,lua_cjson.c:706:5: 错误: ‘for‘ 循环初始化声明只在 C99 或 C++ 模式下允许
开发语言·lua·openresty
qz_Serene5 小时前
C++:类和对象(上)
开发语言·c++
西安景驰电子5 小时前
《PTP精确时间协议系列》第一篇:从原理到应用,全面解读IEEE 1588
linux·运维·服务器·开发语言·网络·windows·php
ctlover5 小时前
Python文件操作
开发语言·python