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要快很多。
- Function 与 Functor 区别
- functor(function object)
- function object (functor) (1)
- function object (functor) (3) : Closure
- 仿函数(functor function objects)
- C++ Review: Function pointer & Function object(functor)
- function 与 new function 区别
- (function ( ){...})( ) 与 (function ( ){...}( )) 有区别
- 泛型算法:Data member 与 member function、functor之间的转换
- Haskell 与 Functor
- Haskell 与 Applicative Functor
- Functor与fmap
- function object (functor) (2) : first-class funtion
- 仿函数functor和function adapters
- std::function & Functor(用 Functor 构造std::function时的注意点)
- Function 与 new Function 的区别
- jQuery(function(){})与(function(){})(jQuery)的区别
- jQuery(function(){ }) 与 (function(){ })(jQuery); 区别
- 某山软件公司 2013开发笔试
- HDU 3746 Cyclic Nacklace(KMP,最短循环节)
- FTP服务器的参数配置
- ThinkingRock:最好的GTD软件
- Android反编译工具集合贴
- Function 与 Functor 区别
- 你们有没有在一起:伤感日志
- 2012杭州QCon全球软件开发大会所见所闻所悟
- C#调用C++动态链接库方法简介
- itoa()其中指定转换的进制
- 嵌入式Linux字符设备驱动程序的主要数据结构
- 叶飘落,诉说着冷寂与孤独
- linux内核网址
- C++运算符重载