C++之函数对象包装器及bind的应用

C++11里面,对函数进一步封装:
函数对象包装器的应用,为函数指针提供一个容器,如下代码:
把函数当成对象来处理;
std::function -> 代表了一个函数对象;

普通函数案例:

#include <iostream>
#include<functional>
#include<vector>

using namespace std;

int test(int n)
{
    return 2+n;
}

int main(void)
{
    test(3);
    //下左边的第一int是返回值,第二个int是参数列表
    std::function<int(int)> f = test; //为函数指针提供了一种指针容器
    cout<<f(123)<<endl;

    return 0;
}

输出结果:

125

匿名函数案例,代码如下:

#include <iostream>
#include<functional>

using namespace std;

int main(void)
{
    std::function<int(int)> f2 = [=](int n)->int{
      cout<<"n is "<<n<<endl;
      return n;
    };

    f2(30);
    return 0;
}

类的成员函数案例,代码如下:

#include <iostream>
#include<functional>

using namespace std;

class Test
{
public:
    int fun(int n)
    {
        return n + 5;
    }
};

int main(void)
{
    Test t1;
    std::function<int(Test*,int)> f3 = &Test::fun;
    cout<<f3(&t1,5)<<endl;

    return 0;
}

输出结果:

10

仿函数案例,代码如下:

#include <iostream>
#include<functional>

using namespace std;

class Test
{
public:
    int fun(int n)
    {
        return n + 5;
    }

    int operator()(int n) //仿函数
    {
        cout<<n<<endl;
        return n + 10;
    }
};

int main(void)
{
    Test t2;

    std::function<int(Test*,int)> f5 = &Test::operator();
    f5(&t2,40);

    return 0;
}

输出结果:

40

总结:支持四种函数对象的包装的相关函数
(1)普通函数;
(2)lambda 表达式;
(3)类的成员函数
(4)仿函数

bind机制
bind作用:将函数和参数绑定,形成新的对象,代码如下:

#include <iostream>
#include<functional>

using namespace std;

//函数bind(绑定)的作用: 假使有一个函数,参数确定,可以直接绑定,生成新的函数;
void Test(int a, int b, int c)
{
    cout <<a<<b<<c<<endl;
}

int main(void)
{
    //std::bind(Test,1,2,3)会返回一个新的函数,用fun接;
    auto fun = std::bind(Test,1,2,3); //第一种调用方法
    fun();

    auto fun2 = std::bind(Test,1,2,std::placeholders::_1); // 占位符调用机制
    fun2(30);
    return 0;
}

输出结果:

123
1230
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值