C++11 std::function

可调用对象

可调用对象,是可以被调用的实体。

通俗来说:x(...)

满足以下条件之一即可

  • 普通函数 / 静态成员函数
  • 函数指针Ret(*)(Args...)
  • 成员函数指针Ret (C::*)(Args...),调用方式特殊)
  • lambda 表达式对象(本质是编译器生成的类对象)
  • 函数对象 / 仿函数(functor) :定义了 operator() 的类/对象
  • std::function:类型擦除后的可调用包装器
  • std::bind 结果(C++11 起,可调用)

std::function

头文件:#include <functional>
std::function 本质上是一个类型擦除的包装器,统一存放和管理各种类型的可调用对象。

函数签名

cpp 复制代码
template< class >  
class function; /* undefined */

template< class R, class... Args >  
class function<R(Args...)>;

要求里面的 callable 能以 Args... 调用,并且返回值能转成 R

基本用法

cpp 复制代码
// 普通函数 || 函数指针
int add(int a, int b) {return a + b;}

function<int(int, int)> f = add;
int x = f(1, 2);

// lambda 
function<int(int)> f = [](int x){ return ++x; };
int x = f(5);

// 仿函数
struct Mul {
  int operator()(int a, int b) const { return a * b; }
};

function<int(int,int)> h = Mul{};
int z = h(2, 3); // 6

进阶用法

类型擦除带来的统一接口。

这里使用 function 可以放入相同函数类型的不同类型

回调列表
cpp 复制代码
int add(int a, int b) {return a + b;}

struct Mul {
  int operator()(int a, int b) const { return a * b; }
};

vector<function<int(int,int)>> v;
v.push_back(add);
v.push_back(Mul{});

for (auto e : v) {
	e(10, 3);
}
回调参数
cpp 复制代码
void run(std::function<int(int)> op) {
  int r = op(10);
}

run([](int x){ 
	return x * x; 
});

注意事项

空状态

std::function 可以是"空的":

如果对空的 std::function 直接调用,会抛:

  • std::bad_function_call
cpp 复制代码
std::function<void()> f; 
if (!f) { /* 空 */ }

try { 
	f(); 
} catch (const std::bad_function_call&) {
	// ...
}

std::function 绑定安全

相关推荐
bksczm10 分钟前
Linux之日志和线程池、内存池
java·开发语言
笨蛋不要掉眼泪17 分钟前
Java虚拟机:对象复活、引用强度与Stop-The-World
java·开发语言·jvm
布朗克16828 分钟前
Go 入门到精通-33-unsafe 与 CGO
开发语言·后端·golang·unsafe·cgo
157092511341 小时前
【无标题】
开发语言·python·算法
xieliyu.1 小时前
MySQL 存储过程详解:概念、创建与删除全教程
开发语言·数据库·mysql
2zcode1 小时前
项目文档:基于MATLAB最小二乘支持向量机的睡眠分期智能监测系统设计与实现
开发语言·支持向量机·matlab
王维同学1 小时前
Credential Provider、Filter 与 PLAP 的 CLSID 枚举
c++·windows·安全·注册表
twcc_come2 小时前
安全策略配置实验报告
开发语言·php
2601_963870222 小时前
基于Python的晋江文学城热门作品数据分析与可视化
开发语言·python·数据分析
Carlgood-Minecraft2 小时前
随机分位系统破解版 (BPS)Version-B4.2
c++