c++11 std::function demo函数

#include <iostream>
#include <functional>
using namespace std;

function<int(int)> callback;

int (*func1)(int);

int sum1(int a){
    return a;
}

template<typename T>
T sum2(T a){
    return a;
}

struct sum3{
    int operator()(int x){
        return x + 9;
    }
};

template<typename T>
struct sum4{
    T operator()(T a){
        return a - 100;
    }
};

template<typename T>
struct sum5{
    static T func(T a){
        return a + 100;
    }
};

struct sum6{
    static int func(int a){
        return a / 2;
    }
};

struct sum7{
    int func(int a){
        return a * 3;
    }
};

template<typename T>
struct sum8{
    T func(T a){
        return a * 10;
    }
};

int main(){
    //function pointer
    func1 = sum1;
    callback = func1;
    cout << callback(10) << endl;;

    //function
    callback = sum1;
    cout << callback(10) << endl;;

    //template function
    callback = sum2<bool>;
    cout << callback(5) << endl;

    //function object
    callback = sum3();
    cout << callback(20) << endl;
    cout << sum3{}(10) << endl;

    //lambda
    callback = [](int a){
        return a * 2;
    };
    cout << callback(20) << endl;

    //template function object
    callback = sum4<int>();
    cout << callback(50) << endl;

    //template object static function
    callback = sum5<int>::func;
    cout << callback(30) << endl;

    //object static function
    callback = sum6::func;
    cout << callback(50) << endl;

    // std::bind()

    // member function
    sum7 temp;
    callback = bind(&sum7::func, temp, std::placeholders::_1);
    cout << callback(26) << endl;

    // template member function
    sum8<int> func2;
    callback = std::bind(&sum8<int>::func, func2, std::placeholders::_1);
    cout << callback(20) << endl;
    
    // std::function (move and copy)

    // = copy
    std::function<int(int)> callback2 = callback;
    cout << callback2(20) << endl;

    //move
    std::function<int(int)>&& callback3 = std::move(callback);
    cout << callback3(20) << endl;
    cout << callback(20) << endl;

    // () copy
    std::function<int(int)> callback4(callback);
    cout << callback4(20) << endl;
    


    cout << plus<int>()(1, 2) << endl;


    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值