人工智能

C++零基础教程之std:function函数包装器

时间:2010-12-5 17:23:32  作者:IT科技   来源:IT科技  查看:  评论:0
内容摘要:前言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; } 
copyright © 2025 powered by 益强资讯全景  滇ICP备2023006006号-31sitemap