C++使用模板、函数指针、接口和lambda表达式这四种方法做回调函数的区别比较
在C++中,两个类之间存在一种关系,某个类需要另外一个类去完成某一个功能,完成了之后需要告知该类结果,这种最普通最常见的需求,往往使用回调函数来解决。 如题,我总结下来有这么四种方式可以完成这项功能,下面来一一分析: 1、使用模板 // CppTest.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <stdlib.h> #include <math.h> template<typename T> class MathTemplate { int ops1,ops2; int result; public: void Add(int a,int b,T callback) { ops1 = abs(a); /* 实际上这个函数可能非常复杂,非常耗时,这样回调更突显作用*/ ops2 = abs(b); result = ops1+ops2; callback.showResult(result); } }; class Result { public: void showResult(int res) { printf("result = %d\n",res); } }; int _tmain(int argc, _TCHAR* argv[]) { Result reShow; MathTemplate<Result>