内容摘要:前言C++中可调用对象的虽然都有一个比较统一的操作形式,但是定义方法五花八门,这样就导致使用统一的方式保存可调用对象或者传递可调用对象时,会十分繁琐。C++提供了std::function和std::

前言
C++中可调用对象的基础教程虽然都有一个比较统一的操作形式,但是函数定义方法五花八门,这样就导致使用统一的包装方式保存可调用对象或者传递可调用对象时,服务器托管会十分繁琐。基础教程C++提供了std::function和std::bind统一了可调用对象的函数各种操作。不同类型可能具有相同的包装调用形式。使用前记得加上functional头文件。网站模板基础教程
包装普通函数
#include <iostream> #include <string> #include <functional> using namespace std; int Max(int a,函数 int b) { return a > b ? a : b; } void print() { cout << "无参无返回值" << endl; } int main() { function<int(int, int)> funMax(Max); cout << funMax(1, 2) << endl; function<void()> funPrint(print); print(); printData(funMax, 1, 2); return 0; }
包装类的静态方法
#include <iostream> #include <string> #include <functional> using namespace std; class Test { public: static void print(int a, int b) { cout << a + b << endl; } void operator()(string str) { cout << str << endl; } operator FuncPTR() { return print; } }; int main() { //包装类的静态方法 function<void(int, int)> sFunc = Test::print; sFunc(1, 2); return 0; }
包装仿函数
#include <iostream> #include <string> #include <functional> using namespace std; class Test { public: void operator()(string str) { cout << str << endl; } }; int main() { //包装仿函数 Test test; function<void(string)> funTest = test; test("仿函数"); return 0; }
包装转换成函数指针的对象 (operator的隐式转换)
#include <iostream> #include <string> #include <functional> using namespace std; using FuncPTR = void(*)(int, int); class Test { public: static void print(int a, int b) { cout << a + b << endl; } operator FuncPTR() { return print; } }; int main() { //包装转换成函数指针的对象 (operator的
站群服务器隐式转换) Test object; function<void(int,int)> funOPE = object; funOPE(2, 3); return 0; }