c++ std::function作为参数传入函数

本文详细介绍了C++中std::function的使用方法,并着重阐述了在将其作为参数传递时需要遵循的规则。通过实例演示了在不同场景下正确使用std::function的重要性,以及不遵循规则可能导致的编译错误。文章旨在帮助开发者避免常见陷阱,提升代码质量和可靠性。

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

#include <functional>
void hello(int a)
{
std::cout<<a<<std::endl;
}

void call_when(int x,const std::function<void(int)> &f)
{
if(x == 0)
	f(x);
}


	call_when(0,hello);


需要头文件functional,在std::function作为参数使用时,必须加const,否则会报错:

 error C2664: “call_when”: 不能将参数 2 从“void (__cdecl *)(int)”转换为“std::function<_Fty> &”
1>          with
1>          [
1>              _Fty=void (int)
1>          ]


加上const后,错误即消除,可顺利运行。

### 将C++函数作为参数递给 `std::function` `std::function` 是 C++ 标准库中的一个类模板,用于存储任何可调用的目标,比如普通函数、lambda 表达式、绑定表达式或其他函数对象。下面通过具体例子展示如何将不同类型的 C++ 函数作为参数递给 `std::function`. #### 使用成员函数 当希望使用类的成员函数时,可以像下面这样做: ```cpp #include <iostream> #include <functional> struct IntDiv { float operator()(int x, int y) const { return static_cast<float>(x) / y; } }; void executeDivision(std::function<float(int, int)> divFunc) { std::cout << "Result: " << divFunc(5, 3) << "\n"; } int main() { IntDiv divisor; // 创建 std::function 对象并赋值为 IntDiv 的实例化操作符重载版本 auto func = std::function<float(int, int)>(divisor); // 调用执行除法运算的方法并将 std::function 实例传入 executeDivision(func); return 0; } ``` 这段代码展示了如何创建一个接受两个整数参数返回浮点数的结果的 `std::function` 类型,并将其初始化为某个特定的对象(这里是 `IntDiv` 结构体的一个实例)。之后此 `std::function` 可以被当作普通的回调机制来使用。 #### 使用自由函数 对于全局范围内的简单函数,则可以直接指定其地址给 `std::function`: ```cpp #include <iostream> #include <functional> // 定义一个简单的二元算术函数 float divide(int numerator, int denominator) { if(denominator != 0){ return static_cast<float>(numerator) / denominator; }else{ throw std::invalid_argument("Denominator cannot be zero"); } } void performOperation(std::function<float(int,int)> op) { try { std::cout << "Performing operation with provided function...\n"; std::cout << "Outcome is : " << op(8, 4) << '\n'; } catch(const std::exception& e) { std::cerr << "Error occurred during execution:" << e.what(); } } int main(){ // 构造 std::function 并指向 divide 自由函数 std::function<float(int,int)> divisionOp(&divide); // 执行带有自定义操作的操作过程 performOperation(divisionOp); return 0; } ``` 这里说明了如果要封装的是非成员函数的情况下的做法——只需提供相应的指针即可完成转换[^1].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值