欢迎来到 安卓源码空间!
安卓源码空间

                                C++高级——function应用及底层实现



function

function 这个东西我了解也不是很多,如有错误,请大佬们指正。

function是一个函数包装器模板,最早来自boost库。在c11标准中将其纳入标准库。该函数包装器模板可以包装任何类型的可调用元素,例如普通函数和函数对象
我老师说,function最大的作用就是保留可调用元素的类型

function的应用

我们先随便写几个函数:

void hello1()
{  cout << "hello world!" << endl;
}
void hello2(string str) // 类型void (*pfunc)(string)
{  cout << str << endl;
}
int sum(int a, int b)
{  return a + b;
}
class Test
{
public: // 必须依赖一个对象void (Test::*pfunc)(string)  void hello(string str) { cout << str << endl; }
};

然后在主函数中使用function:
function使用:function<返回值类型(参数类型)>

int main()
{  function<void()> func1 = hello1;  func1(); // func1.operator()() => hello1()  function<void(string)> func2 = hello2;  func2("hello hello2!"); // func2.operator()(string str) => hello2(str)  function<int(int, int)> func3 = sum;  cout<<func3(20, 30)<<endl;  // operator()  function<int(int, int)> func4 = [](int a, int b)->int {return a + b; };  cout << func4(100, 200) << endl;  function<void(Test*, string)> func5 = &Test::hello;  func5(&Test(), "call Test::hello!");  return 0;
}

先是用函数类型实例化function
然后通过function调用相应的operator()函数,传入相应参数

其中fun4直接对lambda表达式进行了一个封装,使其能够达到和sum函数等同的效果。
func5由于在类中所以要多传入一个Test*来代替类中的this指针

看到这里,不禁有个想法?
我直接调用函数不好么?为啥要脱裤子放屁。

后来老师给我演示了这么一个例子:

void doShowAllBooks() { cout << "查看所有书籍信息" << endl; }
void doBorrow() { cout << "借书" << endl; }
void doBack() { cout << "还书" << endl; }
void doQueryBooks() { cout << "查询书籍" << endl; }
void doLoginOut() { cout << "注销" << endl; }

int main()
{  int choice = 0;  //       C的函数指针  map<int, function<void()>> actionMap;  actionMap.insert({ 1, doShowAllBooks }); // insert(make_pair(xx,xx));  actionMap.insert({ 2, doBorrow });  actionMap.insert({ 3, doBack });  actionMap.insert({ 4, doQueryBooks });  actionMap.insert({ 5, doLoginOut });  for (;;)  {  cout << "-----------------" << endl;  cout << "1.查看所有书籍信息" << endl;  cout << "2.借书" << endl;  cout << "3.还书" << endl;  cout << "4.查询书籍" << endl;  cout << "5.注销" << endl;  cout << "-----------------" << endl;  cout << "请选择:";  cin >> choice;  auto it = actionMap.find(choice); // map  pair  first second  if (it == actionMap.end())  {  cout << "输入数字无效,重新选择!" << endl;  }  else  {  it->second();  }  return 0;
}

取代了原来笨逼且违反开闭原则的switch——case操作:

/*switch (choice)
		{
		case 1:
			break;
		case 2:
			break;
		case 3:
			break;
		case 4:
			break;
		case 5:
			break;
		default:
			break;
		}*/ 

在这里插入图片描述
而且function能很好的避免以前c++遍地都是类的局面。其实现函数对象机制更能使得编译器实现内联调用,减少函数调用开销。

function实现原理

//R为返回值类型,A是传入的参数类型
template<typename R, typename... A>
class myfunction<R(A...)>
{
public:  using PFUNC = R(*)(A...);  myfunction(PFUNC pfunc) :_pfunc(pfunc) {}  R operator()(A... arg)  {  return _pfunc(arg...); // hello(arg)  }
private:  PFUNC _pfunc;
};


利用template的强大机制,用...表示多个传入的参数。
避免了因为参数的个数不同重写多个myfunction。
诺,就是这样:

template<typename R, typename A1>
class myfunction<R(A1)>
{
public:  using PFUNC = R(*)(A1);  myfunction(PFUNC pfunc) :_pfunc(pfunc) {}  R operator()(A1 arg)  {  return _pfunc(arg); // hello(arg)  }
private:  PFUNC _pfunc;
};
template<typename R, typename A1, typename A2>
class myfunction<R(A1, A2)>
{
public:  using PFUNC = R(*)(A1, A2);  myfunction(PFUNC pfunc) :_pfunc(pfunc) {}  R operator()(A1 arg1, A2 arg2)  {  return _pfunc(arg1, arg2); // hello(arg)  }
private:  PFUNC _pfunc;
};
*/

说白了,这个就是对函数的一种包装,本质还是调用那个函数。

参考文献

[1] 施磊.腾讯课堂——C++高级.图论科技,2020.7.
[2]小天_y,博客园,https://www.cnblogs.com/yyxt/p/3987717.html,2014-9-23.

————————————————

                            版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。                        
                            原文链接:https://blog.csdn.net/shenmingxueIT/article/details/107545633

copyright@ 2020-2028  安卓源码空间网版权所有   

备案号:豫ICP备2023034476号-1号