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

相关推荐
FuckPatience1 小时前
Visual Studio C# 项目中文件后缀简介
开发语言·c#
老四啊laosi7 小时前
[C++进阶] 24. 哈希表封装unordered_map && unordered_set
c++·哈希表·封装·unordered_map·unordered_set
014-code8 小时前
订单超时取消与库存回滚的完整实现(延迟任务 + 状态机)
java·开发语言
妙为8 小时前
银河麒麟V4下编译Qt5.12.12源码
c++·qt·国产化·osg3.6.5·osgearth3.2·银河麒麟v4
lly2024068 小时前
组合模式(Composite Pattern)
开发语言
游乐码8 小时前
c#泛型约束
开发语言·c#
Dontla9 小时前
go语言Windows安装教程(安装go安装Golang安装)(GOPATH、Go Modules)
开发语言·windows·golang
chushiyunen9 小时前
python rest请求、requests
开发语言·python
铁东博客9 小时前
Go实现周易大衍筮法三变取爻
开发语言·后端·golang
baidu_huihui9 小时前
在 CentOS 9 上安装 pip(Python 的包管理工具)
开发语言·python·pip