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 绑定安全

相关推荐
倒头就睡的小比特4 天前
算法竞赛C++常用的STL
c++·算法
weilx12344 天前
C++笔记-文件IO-<fcntl.h>
c++
小羊没烦恼!4 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
伞伞悦读4 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
Smileyqp沛沛4 天前
前端?C++ ?较大差异基础罗列
c++·基础·前端转c++
C语言小火车4 天前
C/C++ 为什么需要编译器?
开发语言·c++
旖旎夜光4 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
吞下星星的少年·-·4 天前
C++ 萌新语法入门篇
c++·算法比赛
霍霍的袁4 天前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio
another heaven4 天前
【算法/C++ MD5算法能否逆解码?原理、C++实现与同类哈希算法对比】
c++·算法·哈希算法