C++11 新特性 ④ | 模板类 std::function 和标准库函数 std::bind

本文介绍了C++11中的std::function和std::bind,阐述了它们如何增强C++的灵活性。std::function提供了一种类型安全的方式来包装和调用可调用实体,而std::bind则允许预绑定函数参数,创建新的可调用对象。通过std::bind和std::function的组合,开发者可以更便捷地实现函数回调和定制化调用逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

好的,以下是一个使用C语言实现std::bindstd::function的示例程序: ```c #include <stdio.h> #include <stdlib.h> // 定义一个函数指针类型 typedef int (*FuncPtr)(int, int); // 定义一个结构体,用于存储函数指针绑定的参数 typedef struct { FuncPtr func; int arg1; int arg2; } BindData; // 定义一个函数类型,用于作为std::function的模板参数 typedef int (*FuncType)(int, int); // 定义一个函数,用于将绑定的参数函数指针传递给std::function int callFunc(void* data, int arg) { BindData* bindData = (BindData*)data; return bindData->func(bindData->arg1, bindData->arg2 + arg); } // 定义一个函数,用于创建std::function对象 void* createFunction(FuncPtr func, int arg1, int arg2) { BindData* bindData = (BindData*)malloc(sizeof(BindData)); bindData->func = func; bindData->arg1 = arg1; bindData->arg2 = arg2; return (void*)bindData; } // 定义一个函数,用于销毁std::function对象 void destroyFunction(void* data) { BindData* bindData = (BindData*)data; free(bindData); } // 定义一个函数,用于测试std::bindstd::function int add(int a, int b) { return a + b; } int main() { // 使用std::bind绑定参数 auto add5 = std::bind(add, std::placeholders::_1, 5); printf("%d\n", add5(10)); // 输出15 // 使用std::function调用绑定了参数的函数 FuncType func = (FuncType)createFunction(add, 10, 5); printf("%d\n", func(3, callFunc(func, 2))); // 输出20 // 销毁std::function对象 destroyFunction((void*)func); return ; } ``` 注意:这只是一个示例程序,实际上C语言并没有std::bindstd::function这两个库函数
评论 34
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dvlinker

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值