function和bind使用实践

1.functional 接受全局函数

2.functional 接受lambda表达式

3.functional 接收静态成员函数

4.functional 接收成员函数

5.bind 绑定全局函数

6.bind 绑定成员函数

7.使用 placeholders占位

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值