cen's blog cen's blog
首页
  • 编程文章

    • markdown使用
  • 学习笔记

    • C++学习
    • C++数据结构
    • MySQL
    • Linux
    • 网络编程
算法
  • CLion
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 分类
  • 标签
  • 归档
关于
GitHub (opens new window)

cen

十年饮冰,难凉热血
首页
  • 编程文章

    • markdown使用
  • 学习笔记

    • C++学习
    • C++数据结构
    • MySQL
    • Linux
    • 网络编程
算法
  • CLion
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 分类
  • 标签
  • 归档
关于
GitHub (opens new window)
  • 类和对象
  • 内存管理
  • 泛型模板
  • string
  • vector
  • list
  • stack和queue
  • priority_queue
  • 继承
  • 多态
  • set和map
  • bitset
  • C++11
  • 异常
  • 智能指针
  • 特殊类设计
  • function包装器
  • 右值引用和移动语义
  • C++学习笔记
cen
2025-08-16

function包装器

function 是一种函数包装器,也叫做适配器。它可以对可调用对象进行包装,本质就是一个类模板。

#include <iostream>

#include <functional>
using namespace std;

int add(int a, int b) {
    return a + b;
}

class Functor {
public:
    int operator()(int a, int b) {
        return a + b;
    }
};

class Add {
public:
    static int intAdd(int a, int b) {
        return a + b;
    }

    double doubleAdd(double a, double b) {
        return a + b;
    }
};

int main() {
    //1、包装函数指针(函数名)
    function<int(int, int)> func1 = add;
    cout << func1(1, 2) << endl;

    //2、包装仿函数(函数对象)
    function<int(int, int)> func2 = Functor();
    cout << func2(1, 2) << endl;

    //3、包装lambda表达式
    function<int(int, int)> func3 = [](int a, int b) { return a + b; };
    cout << func3(1, 2) << endl;

    //4、类的静态成员函数
    //function<int(int, int)> func4 = Plus::plusi;
    function<int(int, int)> func4 = &Add::intAdd; //&可省略
    cout << func4(1, 2) << endl;

    //5、类的非静态成员函数
    function<double(Add, double, double)> func5 = &Add::doubleAdd; //&不可省略
    cout << func5(Add(), 1.1, 2.2) << endl;
    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
上次更新: 2025/09/03, 18:26:17
特殊类设计
右值引用和移动语义

← 特殊类设计 右值引用和移动语义→

最近更新
01
网络协议
09-03
02
套接字和TCP
08-26
03
常用数据结构
08-23
更多文章>
Theme by Vdoing | Copyright © 2024-2025 京ICP备2020044002号-3 京公网安备11010502056119号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式