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;
}
相关推荐
weixin_429630266 分钟前
实验二-决策树-葡萄酒
算法·决策树·机器学习
草莓熊Lotso24 分钟前
C++ 方向 Web 自动化测试入门指南:从概念到 Selenium 实战
前端·c++·python·selenium
Olrookie36 分钟前
若依前后端分离版学习笔记(二十)——实现滑块验证码(vue3)
java·前端·笔记·后端·学习·vue·ruoyi
茉莉玫瑰花茶1 小时前
floodfill 算法(dfs)
算法·深度优先
533_1 小时前
[vue] dayjs 显示实时时间
前端·javascript·vue.js
CoderCodingNo1 小时前
【GESP】C++五级考试大纲知识点梳理, (5) 算法复杂度估算(多项式、对数)
开发语言·c++·算法
lpfasd1231 小时前
第2部分:Netty核心架构与原理解析
运维·服务器·架构
若尘拂风1 小时前
centos 7.9 编译安装 freeswitch 1.10.12
服务器·udp·freeswitch·sip
故事与他6452 小时前
XSS_and_Mysql_file靶场攻略
前端·学习方法·xss
小蜜蜂爱编程2 小时前
gerrit的部署与配置关联到不同服务器上的git仓库
运维·服务器·git·gerrit