定义:重载了()操作符的类/结构体
#include二、使用#include #include using namespace std; //定义了一个函数对象(仿函数) struct MyTest { void operator()(string msg) // 重载了()运算符 { cout << msg << endl; } }; int main(void) { MyTest t; t("mata"); //像函数一样调用 return 0; }
#include#include #include using namespace std; // 函数对象 template struct LessThan { LessThan(const T& threshold){ this->_threshold = threshold; } bool operator()(const T& value1) // 重载了()operator { return value1 < _threshold; //非基础类型 要重载 < operator } T _threshold; }; int countIf(int* begin, int* end, std::function func) { int count = 0; for (int* pt = begin; pt != end; pt++) { count = func(*pt) ? count + 1 : count; //调用了bool operator()(const T& value1) } return count; } int main() { int arr[5] = { 1, 2, 13, 14,15 }; // 统计小于10的个数 LessThan a(10); // 传递一个可调用对象(这里是一个函数对象) int count = countIf(arr, arr + 5, a); // 传递一个匿名的可调用对象(这里是一个函数对象) int count1 = std::count_if(arr, arr + 5, LessThan (10)); std::cout << count << std::endl; std::cout << count1 << std::endl; }



