C++11函数对象包容器

#include<iostream>
#include<functional>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
int test(int n)
{
    cout << n << endl;
    return 1;
}
class CTest 
{
public:
    int Mytest(int n) {
        cout << n << endl;
        return n;
    }
    int operator()(int n) {
        cout << n << endl;
        return n;
    }
};
int test04(int a, int b, int c, int d)
{
    return a + b + c + d;
}
int main()
{
    //函数对象包装器
    //为了函数提供了一种容器(封装)
    test(1);
    //四种函数类型,
    //1.普通函数
    std::function<int(int)> f = test;
    //function表示函数对象,因为函数类型很多,所以这里提供的是一种模板的写法
    //返回值(参数列表)
    f(1);

    //2.匿名函数
    int a = 10;
    std::function<int(int)> f2 = [a](int n)mutable->int {
        return n;
        cout << n + a << endl;
    };
    cout << f2(10);

    //3.类的成员函数
    std::function<int(CTest*, int)> f3 = &CTest::Mytest;
    CTest ct;
    f3(&ct, 10);

    ct(123);
    return 0;

    //4.仿函数
    std::function<int(CTest*, int)>f4 = &CTest::operator();
    f4(&ct, 123);


    //bind机制,如果函数中的参数比较多,不能在调用时候第一时间给全部赋值,这个时候就需要bind绑定
    // 将参数1,2绑定到函数 foo 上,但是使用 std::placeholders::_1 来对第一个参数进行占位
    auto bindFoo = std::bind(test04, std::placeholders::_1, 2, 3, 4);
    // 这时调用 bindFoo 时,只需要提供第一个参数即可
    bindFoo(1);

    // 将参数1,2绑定到函数 foo 上,但是使用 std::placeholders::_1 来对第一个参数进行占位
    auto bindFoo = std::bind(test04, std::placeholders::_2, std::placeholders::_1, 3, 4);
    // 这时调用 bindFoo 时,只需要提供第一个参数即可
    bindFoo(1,2);//1对应的是上面的1(第二个参数),2对应的是上面的2(第一个参数)。
    


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值