std::function函数 与std::bind

//
// Created by cuizhou on 18-9-13.
//

#include <iostream>
#include <functional>

using namespace std;

void printA(int a){
    cout << a << endl;
}

void printB(int a, int b){
    cout << a << " " << b << endl;
}

template <typename T>
void printT(T t){
    cout << t << endl;
}

class Print{
public:
    static void print1(int a){cout << a << endl;}
    void print2(int a){cout << a << endl;}
    void print3(int a, int b){cout << a << " " << b << endl;}
};

template <typename T>
class PrintT{
public:
    static void printT1(T t){cout << t << endl;}
    void printT2(T t){cout << t << endl;}
};


void test_std_function(){
    // old way to use
    typedef void (*F)(int);
    F func1 = printA;                   // normal function
    func1(1);

    func1 = [](int a){printA(a);};      // lambda
    func1(2);

    func1 = (&Print::print1);           // static class member function
    func1(3);

    Print p = Print();                  //  static class member function
    func1 = (p.print1);
    func1(4);

    func1 = printT<int>;                // template function
    func1(5);

    PrintT<int> pT = PrintT<int>();     // static template class member function
    func1 = (pT.printT1);
    func1 = &PrintT<int>::printT1;
    func1(6);


    // use std::fuction
    std::function<void (int)> func2;    // normal function
    func2 = printA;
    func2(7);

    func2 = [](int a){printA(a);};      // lambda
    func2(8);

    func2 = (&Print::print1);           // static class member function
    func2(9);

    func2 = (p.print1);                 // static class member function
    func2(10);

    func2 = printT<int>;                // template function
    func2(11);

    func2 = pT.printT1;                 // static template class member function
    func2 = &PrintT<int>::printT1;
    func2(12);

    // std::bind
    func2 = std::bind(&Print::print2, &p, placeholders::_1); // non-static class member function
    func2(13);

    func2 = std::bind(&PrintT<int>::printT2, &pT, placeholders::_1); // non-static template class member function
    func2(14);

    auto func3 = std::bind(&Print::print3, &p, placeholders::_1, placeholders::_2);
    func3(15,16);

    auto func4 = std::bind(printB, placeholders::_1, placeholders::_2);
    func4(17,18);

    auto func5 = std::bind(printB, 19, placeholders::_1);
    func5(20);
}

int main(){
    test_std_function();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值