上期讲了函数指针这一期讲函数对象,就是通过对象去重载()运算符去调用
让高级函数去调用不同的函数
函数指针
匿名函数
回调函数
function和bind
#include <iostream>
#include <vector>
using namespace std;
// 因为le(x,y)形式 类似于函数调用 以此le成为函数对象 其实就是一个类的普通对象而已
template<typename T>
class LessThan {
public:
bool operator()(T a, T b)const { return a < b; }
};
template<typename T,typename CompareT> // CompareT 接受所有类型 下面丢的一个类对象函数
T find_optimal(const vector<T>arr, const int n, CompareT compare) { //这个模板带了两个参数一个函数对象
T opt{ arr[0] };
for (auto i = 1; i != n; i++)
if (compare(arr[i], opt)) //arr[i] 比opt更好 arr[i] 在遍历比较 这里调用函数
opt = arr[i];
return opt;
}
template<typename T>
bool greate(const T& a, const T& b) { return a >= b; }
bool lessAbs(const double& a, const double& b) { return abs(a) < abs(b); }
int main() {
vector<double>a{ 9,-3,2,-7 };
cout << find_optimal(a, 4, LessThan<double>()) << '\t'; // LessThan<double>()传递的函数对象
cout << find_optimal(a, 4, greate<double>) << '\t'; // 丢的普通模板函数
cout << find_optimal(a, 4, lessAbs) << '\t'; // 丢的普通函数
while (true);
return 0;
}
//double x{ 3 }, y{ 4 };
//LessThan le;
//if (le(x, y)) // 这是一种简写方法实际 le.operator()(x,y)
// cout << "x<y\n";