Function 与 Functor 区别

来源:互联网 发布:mastercam编程 编辑:程序博客网 时间:2024/05/17 22:32

转:http://blog.sina.com.cn/s/blog_54b8fc360100bhxd.html

Function几乎是任何语言的元素之一,从Pascal,Fortran到C++,VB,几乎任何时代的语言都支持它。在C++里,随着 C++标准库的推出,人们开始渐渐的接触到另一种定义函数的方式:Functor。所谓Functor,其实就是重载了operator () 的类其使用方式和普通函数差不多(这正是C++处处体现的一种思想:只在定义上有区别,在使用上毫无区别)。


譬如说,如果我们要定义一个函数,将传入的整型引用加一,我们可以有两种方法定义
inline void increase_one_func(int& i){  ++i;}class increase_one_functor{public:  void operator()(int& i)  {    ++i;  }}


使用起来则没什么区别
int i=0;increase_one_func(i);increase_one_functor(i);

那Function和Functor到底有什么区别呢?其实他们定义方式的区别已经决定了他们使用上的区别了。

首先,Functor相比Function来说,可以传递更多的信息:
因为Functor是以类的方式存在的,它可以包含任意多的信息。除了传入参数以外,你还可以在类内预设一些其它的信息。
譬如说,下面这个Functor:
class increase_one_functor{  int mIncrement;public:  increase_one_functor(int increment=1):mIncrement(increment)  {}  void operator()(int& i)  {    ++i;  }}

可以很方便的实现将一个整数增加任意值的功能:
increase_one_functor(100)(i);// 将i加100。
而Function就很难实现这样的可扩展性。

  其次,在作为参数传递时,Functor的效率往往比Function要高。这是因为,在把Functor作为参数传递时,你实际上传递的是Functor对象,在整个编译过程中,编译器始终知道它所在处理的Functor对象是哪个Functor类的,也就是说,它可以做编译时的优化。而对于Function来说,它往往以指针的方式传递,对于编译器来说,很难做(并不是不可能)编译时的优化。


下面这段程序或许可以说明问题:
#include <windows.h>#include <iostream>using namespace std;inline void increase_one_func(int& i){  ++i;}class increase_one_functor{public:  void operator()(int& i)  {    ++i;  }}increase_one_functor;const int VECTOR_SIZE=1024*16;void treat_vector_func(int ai[VECTOR_SIZE],void (*func)(int& i)){  for(int i=0;i<VECTOR_SIZE;++i)    func(ai[i]);}template<typename T>void treat_vector_func(int ai[VECTOR_SIZE],T functor){  for(int i=0;i<VECTOR_SIZE;++i)    functor(ai[i]);}void main(void){  static int ai[VECTOR_SIZE];  const int CALL_TIMES=10240;  {    long l=GetTickCount();    for(int i=0;i<CALL_TIMES;++i)      treat_vector_func(ai,increase_one_func);    l=GetTickCount()-l;    cerr<<"function "<<l<<endl;  }  {    long l=GetTickCount();    for(int i=0;i<CALL_TIMES;++i)      treat_vector_func(ai,increase_one_functor);    l=GetTickCount()-l;    cerr<<"functor "<<l<<endl;  }}


运行结果如下:
Debug模式下(也就是说,没有任何优化的情况下):
function 37623
functor 36825
Release模式下:
function 4573
functor 1726
可见,functor比function要快很多。
原创粉丝点击