C++第13课 智能指针 (二)

1.函数包装器

/*
    1.包含functional
    2.作用: 把函数指针,函数对象,函数等,包装成一个对象
    3.function<type> object(functionObject);
        type:返回值类型(参数类型)
*/
int Max(int a, int b) 
{
    return a > b ? a : b;
}
using FucPTR = void(*)(int, int);
class  Test 
{
public:
    static void print(int a, int b) 
    {
        cout << a + b << endl;
    }
    void operator()(string str) 
    {
        cout << str << endl;
    }
    operator FucPTR() 
    {
        return print;
    }
};
template <class _Ty>
void printData(_Ty object,int a,int b) 
{
    cout << object(a, b) << endl;;
}
int main() 
{
    //1.包装普通函数
    function<int(int, int)> fMax(Max);
    cout << fMax(2, 3) << endl;
    //2.包装类的静态方法
    function<void(int, int)> testPrint(Test::print);
    testPrint(1,2);
    //3.包装仿函数
    Test test;
    function<void(string)> func=test;
    func("仿函数");
    //4.包装转换成函数指针的对象
    function<void(int, int)> func2 = test;
    func2(3,4);
    printData([](int a, int b) {return a + b; }, 1, 3);
    printData(fMax, 2, 3);
    return 0;
}

2.函数适配器

/*
     //bin1st bind2nd  淘汰了
     bind函数: 函数适配器,绑定一个参数,一般绑定,意味着这个参数就不需要传入,意味着这个参数不存在了
     不绑定可以用占位符表示, std::placeholders::_1 
     bind函数返回的是一个对象,类似函数包装器的对象,可以直接当做函数指针使用
*/
int  Max(int a, int b) 
{
    cout << a << endl;
    cout << b << endl;
    return a > b ? a : b;
}
class Test 
{
public:
    void printTest(int a, int b, int c) 
    {
        cout << "a=" << a << endl;
        cout << "b=" << b << endl;
        cout << "c=" << c << endl;
    }
};
void print(int a, double b, string c) 
{
    cout << a << endl;
    cout << b << endl;
    cout << c << endl;
}
int main() 
{
    //1.绑定普通函数
    auto pMax = bind(Max, std::placeholders::_1, 200);
    cout << pMax(1) << endl;;
    auto pMax2 = bind(Max, 2, 3);
    cout << pMax2() << endl;;
    //2.绑定类中的成员函数指针
    Test test;
    auto  testFunc = bind(&Test::printTest, &test, std::placeholders::_1, 22, 33);
    testFunc(11);
    //3.容器的一些算法常用
    vector<int> data = { 1,2,3,4,5,6,7,8,9 };
    cout << count_if(data.begin(), data.end(), 
        bind(greater<int>(),std::placeholders::_1,6))<<endl;
    cout << count_if(data.begin(), data.end(),
        [](int a, int b = 6) {return a > b; }) << endl;
    //4.结合函数包装器实现不同形态的包装对象
    //4.1 正常包装
    function<void(int, double, string)> f1 = print;
    f1(1, 1.11, "正常包装");
    //4.2 正常的适配与包装
    function<void(int, double)> f2 = bind(print, placeholders::_1, placeholders::_2, "正常适配");
    f2(2,2.2);
    //4.3调整参数顺序进行绑定
    //void print(int a, double b, string c) 
    auto  f3 = bind(print, placeholders::_2, placeholders::_1, "调整参数");
    f3(3.3, 3);
    function<void(double,int)>  f4 = bind(print, placeholders::_2, placeholders::_1, "调整参数");
    f4(3.3, 3);
    //4.4 调整所有参数
    function<void(string, int, double)> f5 = bind(print, 
        placeholders::_2, placeholders::_3, placeholders::_1);
    f5("调整所有参数", 4, 4.4);
    //bind主要使用在回调函数中
    return 0;
}

 

posted @ 2021-09-11 16:34  Creature_lurk  阅读(39)  评论(0编辑  收藏  举报