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;
}
相关推荐
玖玥西1 小时前
html5——CSS3_文本样式属性
前端·css·html·css3·html5·web
机智的土拨鼠1 小时前
解决本地操作云服务器上的Redis
java·linux·服务器·windows·redis·ubuntu
卓卓没头发1 小时前
Vue Router 4:构建高效单页面应用的路由管理
前端·javascript·vue.js
明湖底的炼丹炉2 小时前
混合贪心算法求解地铁线路调度
算法·贪心算法
国中之林3 小时前
【qt】TCP的监听 (设置服务器IP地址和端口号)
服务器·qt·学习·tcp/ip·php
码农鑫哥的日常3 小时前
DHCP与TCP的简单解析
服务器·网络·tcp/ip
2301_784912693 小时前
关于美国服务器IP的几个常见问题
服务器
中云DDoS CC防护蔡蔡3 小时前
SDK游戏盾、高防IP和高防CDN有什么区别
运维·服务器·tcp/ip·http·ddos
SuGarSJL4 小时前
npm ERR! code ENOTEMPTY npm ERR! syscall rename npm ERR!
前端·npm·node.js
云边有个稻草人4 小时前
【C语言】自定义类型:联合和枚举
c语言·开发语言·算法