c++中如何使用std::function封装函数_std::function的用法与实践

std::function 是 C++ 中用于封装可调用对象的通用包装器,定义于 <functional> 头文件。它支持普通函数、lambda 表达式、成员函数、仿函数等,语法为 std::function<返回类型(参数列表)>,常用于回调机制、函数表和延迟执行。例如:std::function<void()> func = [](){ std::cout << “Hello”; }; func(); 可统一调用不同形式的函数对象。使用时需注意其类型擦除带来的轻微性能开销及空值检查以避免异常。

c++中如何使用std::function封装函数_std::function的用法与实践

在C++中,std::function 是一个通用的多态函数包装器,定义在 <functional> 头文件中。它可以封装各种可调用对象,比如普通函数、函数指针、lambda表达式、绑定表达式(bind)以及仿函数(functor),提供统一的调用方式,是实现回调机制、事件处理、延迟执行等场景的重要工具

基本语法与定义

std::function 的模板参数是一个函数签名,格式为:std::function<返回类型(参数类型…)>

例如:

  • std::function<int(int, int)> 可以保存接受两个int并返回int的可调用对象。
  • std::function<void()> 表示无参数无返回值的函数包装。

使用前需包含头文件:

立即学习C++免费学习笔记(深入)”;

#include <functional>

封装不同类型的可调用对象

std::function 能统一处理多种调用形式,下面展示常见用法。

1. 封装普通函数

void greet() {
std::cout << “Hello, World!” << std::endl;
}

std::function<void()> func = greet;
func(); // 输出: Hello, World!

2. 封装lambda表达式

std::function<int(int, int)> add = [](int a, int b) {
return a + b;
};

int result = add(3, 4); // result = 7

3. 封装成员函数

成员函数需要绑定对象实例,通常结合 std::bind 或使用lambda捕获this。

class Calculator {
public:
int multiply(int a, int b) {
return a * b;
}
};

Calculator calc;
std::function<int(int, int)> mul = std::bind(&Calculator::multiply, &calc, std::placeholders::_1, std::placeholders::_2);
int val = mul(3, 5); // val = 15

或使用lambda:

c++中如何使用std::function封装函数_std::function的用法与实践

Topaz Video AI

一款工业级别的视频增强软件

c++中如何使用std::function封装函数_std::function的用法与实践169

查看详情 c++中如何使用std::function封装函数_std::function的用法与实践

std::function<int(int, int)> mul_lambda = [&calc](int a, int b) {
return calc.multiply(a, b);
};

4. 封装函数对象(仿函数)

struct Square {
int operator()(int x) const {
return x * x;
}
};

std::function<int(int)> sq = Square{};
int s = sq(4); // s = 16

实际应用场景

1. 回调函数

在异步操作或事件驱动编程中,常用 std::function 作为回调参数。

void execute_task(std::function<void()> callback) {
// 模拟任务执行
std::cout << “Task running…” << std::endl;
callback(); // 执行回调
}

execute_task([]{ std::cout << “Done!” << std::endl; });

2. 函数表(映射操作符到函数)

std::map<char, std::function<double(double, double)>> operations = {
{‘+’, [](double a, double b) { return a + b; }},
{‘-‘, [](double a, double b) { return a – b; }},
{‘*’, [](double a, double b) { return a * b; }},
{‘/’, [](double a, double b) { return b != 0 ? a / b : 0; }}
};

double res = operations[‘+’](2.5, 3.5); // res = 6.0

3. 延迟执行或条件调用

将函数保存起来,在满足条件时再执行。

std::function<void()> deferred_task;

// 设置任务
deferred_task = [] { std::cout << “Executing later…” << std::endl; };

// 条件满足后执行
if (true) {
deferred_task();
}

注意事项与性能

std::function 是类型擦除的实现,内部使用堆存储(小对象优化后可能在上),会有轻微运行时开销,不适合极度性能敏感的内层循环。

空值检查:未初始化或赋值为空的 std::function 调用会抛出 std::bad_function_call 异常。

std::function<void()> f;
if (f) {
f();
} else {
std::cout << “Function is empty.” << std::endl;
}

基本上就这些。std::function 提供了灵活而清晰的方式管理可调用对象,让代码更模块化和可扩展。合理使用,能显著提升接口设计的自由度。

c++ 回调函数 工具 red if 封装 多态 成员函数 include const 回调函数 char int double void 循环 Lambda 指针 接口 class public Struct operator map function 对象 事件 this 异步

上一篇
下一篇
text=ZqhQzanResources