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;
}
相关推荐
彩云回30 分钟前
支持向量机(SVM)
算法·机器学习·支持向量机
Filotimo_4 小时前
2.CSS3.(2).html
前端·css
yinuo5 小时前
uniapp微信小程序华为鸿蒙定时器熄屏停止
前端
Asmalin5 小时前
【代码随想录day 29】 力扣 135.分发糖果
算法·leetcode·职场和发展
微笑尅乐6 小时前
多解法详解与边界处理——力扣7.整数反转
算法·leetcode·职场和发展
夏鹏今天学习了吗6 小时前
【LeetCode热题100(31/100)】K 个一组翻转链表
算法·leetcode·链表
薰衣草23336 小时前
力扣——位运算
python·算法·leetcode
未知陨落6 小时前
LeetCode:83.打家劫舍
算法·leetcode
gnip6 小时前
vite中自动根据约定目录生成路由配置
前端·javascript
云心雨禅6 小时前
WordPress提速指南:Memcached+Super Static Cache+CDN缓存网站内容
linux·服务器·数据库·缓存·memcached