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

相关推荐
纵有疾風起27 分钟前
C++——类和对象(3)
开发语言·c++·经验分享·开源
Full Stack Developme36 分钟前
java.text 包详解
java·开发语言·python
文火冰糖的硅基工坊1 小时前
[嵌入式系统-135]:主流AIOT智能体开发板
开发语言·嵌入式·cpu
承渊政道2 小时前
动态内存管理
c语言·c++·经验分享·c#·visual studio
yudiandian20142 小时前
02 Oracle JDK 下载及配置(解压缩版)
java·开发语言
要加油哦~2 小时前
JS | 知识点总结 - 原型链
开发语言·javascript·原型模式
孤独得猿2 小时前
聊天室项目开发——etcd的安装和使用
linux·服务器·c++·etcd
鄃鳕2 小时前
python迭代器解包【python】
开发语言·python
new coder2 小时前
[c++语法学习]Day10:c++引用
开发语言·c++·学习
驰羽2 小时前
[GO]GORM 常用 Tag 速查手册
开发语言·后端·golang