「C++ 进阶语法」std::function 基本用法

文章大图来源:pixiv_id=107985575

1 基本概念

std::function 是 C++ 标准库中的一个模板类,定义在 <functional> 头文件中。

std::function 是一种通用的、多态的 函数封装器,可以存储、复制和调用任何可调用对象(如函数、函数指针、成员函数指针、lambda 表达式等)

2 基本语法

std::function 其基本语法是 std::function<返回值类型(参数类型列表)> 变量名;

例如 std::function<void(int, std::string)> 定义了一个 存储返回值为 void,接收一个 int 参数和一个 std::string 字符串参数的函数(可调用对象) 的 std::function 对象。

  • 函数指针

    可以将普通函数指针赋值给 std::function 对象:

    1
    2
    3
    4
    5
    6
    void foo(int a, std::string s){
    std::cout << a << ' ' << s << "\n";
    }

    std::function<void(int, std::string)> func = add;
    func(520, "Marisa"); // 520 Marisa
  • lambda 表达式

    Lambda 表达式是一种匿名函数,也可以赋值给 std::function 对象:

    1
    2
    3
    4
    std::function<void(int, std::string)> func = [](int x, std::string){
    std::cout << a << ' ' << s << "\n";
    };
    func(520, "Marisa"); // 520 Marisa
  • 成员函数指针

    对于类的成员函数,需要结合对象实例来使用:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    class MyClass{
    public:
    int foo(int a, int b){
    return a * b;
    }
    };

    MyClass obj; // 创建一个对象实例
    std::function<int(int, int)> func = std::bind(&MyClass::multiply, &obj, std::placeholders::_1, std::placeholders::_2);

    int res = func(2, 3); // 6

    这里使用 std::bind 来绑定成员函数和对象实例,std::placeholders::_1std::placeholders::_2 表示参数占位符,用于在调用 func 时传递参数。


「C++ 进阶语法」std::function 基本用法
https://marisamagic.github.io/2025/01/10/20250110/
作者
MarisaMagic
发布于
2025年1月10日
许可协议