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

相关推荐
码匠许师傅8 分钟前
【C++三方组件】OpenCV:计算机视觉的事实标准
c++
昂好的day10 分钟前
WPF 从零入门(上):WPF 是什么、XAML 语法、布局与样式全解
开发语言·c#·wpf
飞浪纪元[FWC–FE]12 分钟前
Qt 构建排错实录:从 MSB 1009 到生成器选型
开发语言·数据库·qt
fly-iot14 分钟前
【FDE知识库】(1):AI 编程时代开发语言选型分析,云使用go,企业用java,算法python,底层c
开发语言·人工智能·golang
云边有个稻草人14 分钟前
Prometheus Pushgateway教程:离线任务指标上报、Shell与Python示例、远程访问
开发语言·python·prometheus
暴走约伯16 分钟前
【VFX工具链源码拆解 01】总体架构:大型项目特效流程的程序化落地
开发语言·经验分享·3d·unity·架构·游戏引擎
C^h9 小时前
c++ string
开发语言·c++
raindayinrain10 小时前
c++高性能--原子操作,无锁编程,操作顺序
开发语言·c++·性能优化
学逆向的10 小时前
C++ 合并命名空间
开发语言·c++·网络安全
Zhao-Jichao10 小时前
VS2026 打包 C++ 程序生成 EXE,借助 Installer Project 扩展工具
开发语言·c++