function和bind使用实践

文章目录

    • [1.functional 接受全局函数](#1.functional 接受全局函数)
    • [2.functional 接受lambda表达式](#2.functional 接受lambda表达式)
    • [3.functional 接收静态成员函数](#3.functional 接收静态成员函数)
    • [4.functional 接收成员函数](#4.functional 接收成员函数)
    • [5.bind 绑定全局函数](#5.bind 绑定全局函数)
    • [6.bind 绑定成员函数](#6.bind 绑定成员函数)
    • [7.使用 placeholders占位](#7.使用 placeholders占位)

1.functional 接受全局函数

2.functional 接受lambda表达式

3.functional 接收静态成员函数

4.functional 接收成员函数

5.bind 绑定全局函数

6.bind 绑定成员函数

7.使用 placeholders占位

cpp 复制代码
#include <iostream>
#include <functional>
#include <string>

using namespace std;

/*
 * 1.functional 接受全局函数
 * 2.functional 接受lambda表达式
 * 3.functional 接收静态成员函数
 * 4.functional 接收成员函数
 * 5.bind 绑定全局函数
 * 6.bind 绑定成员函数
 * 7.使用 placeholders占位
 * */

void print(string name,int age){
    cout << name << "="<< age << endl;
}

class stu{
public:
    string read(string name,int age){
        return name+ to_string(age) +"岁在看书";
    }

    static void introduce(string name,int age){
        cout << "我是"<< name << age << "岁了"<< endl;
    }
};

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

int main() {
    function<void (string,int)> f1= print;
    f1("小明",12);

    function<int (int,int)> f2 = [](int a,int b){return a+b;};
    int result = f2(1,2);
    cout << "result=" << result << endl;

    function<void (string,int)> fs = stu::introduce;
    fs("小红",15);

    function<string (stu,string,int)> fr = &stu::read;
    stu s1;
    fr(s1,"小丽",8);
    function<string (stu&,string,int)> fr2 = &stu::read;
    stu s2;
    fr2(s2,"小天",100);
    function<string (stu*,string,int)> fr3 = &stu::read;
    stu s3;
    fr3(&s3,"康康",26);

    auto b = bind(add,1,2);
    int result2 = b();
    cout << "result2 = "<< result2 <<endl;
    function<int ()> f3 = bind(add,1,3);
    int result3 = f3();
    cout << "result3 = "<< result3<<endl;

    stu ss;
    stu sa;
    auto b2 = bind(&stu::read,ss,"莎莉",19);
    function<string ()> f4 = bind(&stu::read,sa,"莎莉2",36);
    f4();

    stu s11;
    stu s12;
    auto b3 = bind(&stu::read,s11,placeholders::_1,85);
    b3("阿妹");

    function<string (string,int)> f5 = bind(&stu::read,s12,placeholders::_1,placeholders::_2);
    f5("野鸡",40);
    
    return 0;
}
相关推荐
roman_日积跬步-终至千里16 分钟前
【后端基础】布隆过滤器原理
算法·哈希算法
若兰幽竹30 分钟前
【机器学习】多元线性回归算法和正规方程解求解
算法·机器学习·线性回归
鱼力舟44 分钟前
【hot100】240搜索二维矩阵
算法
林的快手1 小时前
CSS列表属性
前端·javascript·css·ajax·firefox·html5·safari
匹马夕阳2 小时前
ECharts极简入门
前端·信息可视化·echarts
北_鱼2 小时前
支持向量机(SVM):算法讲解与原理推导
算法·机器学习·支持向量机
API_technology2 小时前
电商API安全防护:JWT令牌与XSS防御实战
前端·安全·xss
yqcoder2 小时前
Express + MongoDB 实现在筛选时间段中用户名的模糊查询
java·前端·javascript
xmweisi3 小时前
【华为】报文统计的技术NetStream
运维·服务器·网络·华为认证
十八朵郁金香3 小时前
通俗易懂的DOM1级标准介绍
开发语言·前端·javascript