> 文章列表 > C++函数适配器

C++函数适配器

C++函数适配器

C++函数适配器

  • 什么是函数适配器
    • bind函数基本用法
    • 绑定普通函数
    • 绑定类中成员函数指针
    • 绑定仿函数
    • 结合一些算法使用
    • 结合包装器使用

什么是函数适配器

函数适配,就是让函数指针调用的时候,函数后绑定特定的参数,从而让函数指针存在多种的调用形态。

bind函数基本用法

bind(),第一个参数是函数名,第二个参数可以是 std::placeholders::_1(表示占位第一个参数)–>参数不固定,可以通过传参,当然也有std :: placeholders::_2…

绑定普通函数

#include<iostream>
#include<algorithm>
#include<functional>using namespace std;int Max(int a, int b)
{return a > b ? a : b;
}int main()
{//std :: placeholders ::_ 1 占位符auto p = bind(Max, std::placeholders::_1, 122);cout << p(1) << endl;  //第二个参数固定,只需要传第一个参数就行}

绑定类中成员函数指针

1.bind(),第一个参数写类名限定的函数名,第二个参数&对象
2.学习使用函数指针

#include<iostream>
#include<functional>
#include<string>
#include<algorithm>using namespace std;class Test
{
public:void printDate(int a, int b, int c){cout << a + b + c << endl;}
};
int main()
{//绑定类中成员函数指针Test test;auto fun = bind(&Test ::printDate, &test, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);fun(1, 2, 3);//成员函数指针的使用//方法一:用auto推断auto fun1 = &Test::printDate;(test.*fun1)(1, 2, 3);//方法二:直接写void(Test :: * p1)(int a, int b, int c);p1 = &Test::printDate;(test.*p1)(1, 2, 8);void(Test:: * p2)(int a, int b, int c) = &Test::printDate;(test.*p2)(2, 4, 9);system("pause");return 0;
}

绑定仿函数

结合一些算法使用

#include<iostream>
#include<functional>
#include<algorithm>
#include<vector>
using namespace std;int main()
{vector<int> date = { 46, 89, 17, 89, 90 };auto fun = count_if(date.begin(), date.end(), bind(less<int>(), std::placeholders::_1, 60));cout << "小于60的人数" << fun << endl;system("pause");return 0;
}

结合包装器使用

include<iostream>
#include<functional>
#include<algorithm>using namespace std;void Date(int a, string b, double c)
{cout << "函数适配器和包装器的结合" << endl;
}int main()
{//正常包装function<void(int, string, double)> fun2;fun2(1, "2", 1.1);//正常适配 (一个参数固定的话,这里类型也要写2个)function<void(int, string)> fun1 = bind(Date, std::placeholders::_1, std::placeholders::_2, 1.11);fun1(1, "3");//可以改变参数的位置function<void(string, int)> fun3 = bind(Date, std::placeholders::_2, std::placeholders::_1, 1.11);fun3("2", 1);//这里改变了第一个参数和第二个参数的位置,同时第三个参数固定return 0;system("pause");
}

函数适配器和包装器,在实际使用中可能很少用到,但我们必须要了解,学会使用。