首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >函数包装器模板std::function

函数包装器模板std::function

原创
作者头像
金莲与饼皆失
发布2025-09-05 23:17:47
发布2025-09-05 23:17:47
7100
代码可运行
举报
文章被收录于专栏:标准模板库STL标准模板库STL
运行总次数:0
代码可运行

std::function是一个函数包装器模板,它可以存储、复制和调用任何可调用对象。它是一个类型擦除容器,提供了统一的接口来处理各种可调用实体。

一、基本定义

代码语言:cpp
代码运行次数:0
运行
复制
#include <functional>

std::function<返回值类型(参数类型列表)> 函数对象;

可以存储什么?

std::function可以存储几乎所有可调用对象;

普通函数

代码语言:cpp
代码运行次数:0
运行
复制
int add(int a,int b){
    return a + b;
}
int sub(int x,int y){
    return y - x;
}
void test(void){
    function<int()> f = bind(&add,3,4); // 如果希望不绑定如何参数,参数列表为空
    cout << "function存储普通函数 f()" << f() << endl;
    // 否则,如果想要含参输入
    using namespace std::placeholders;
    function<int(int,int)> f1 = bind(&sub,_1,_2);
    cout << "function存储普通函数 f(int,int)" << f1(1,9) << endl;
}

成员函数(需要特殊处理)

代码语言:cpp
代码运行次数:0
运行
复制
class Math{
public:
    int area(int x , int y) const{
        return x * y;
    }
};
void test0(void){
    Math math;
    using namespace std::placeholders;
    function<int(int,int)> f = bind(&Math::area,&math,_1,_2);
    cout << "成员函数f() " << f(3,3) << endl; 
}

函数指针

代码语言:cpp
代码运行次数:0
运行
复制
int add(int a,int b){
    return a + b;
}
void test2(void){
    // 定义函数指针
    int (*func_ptr)(int,int) = &add;
    function<int(int,int)> f = func_ptr;
    cout << "绑定函数指针" << f(5,6) << endl;
}

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档