正好碰到了C++的函数对象,查各路资料,总结写下来吧

来源:互联网 发布:淘宝 淘气值 编辑:程序博客网 时间:2024/05/23 14:56

       DTL中的BCA和BPA都是函数对象,如BCA的文档所说 A BCA is a function object (this can be a wrappedfunction pointer if you use cb_ptr_fun()) that is called to create an association between the columns in a SQL view  and the fields in a user defined data object that is used to represent individual rows from the view. Supported C++ types for binding to the fields in a database are shown in the BoundIO documentation.

        函数对象function object,实质上是一个实现了operator()--括号操作符--的类,BCA的一个代码如下:

class BCAExampleObj{public:void operator()(BoundIOs &cols, Example &rowbuf)    {   cols["INT_VALUE"] >> rowbuf.exampleInt;   cols["STRING_VALUE"] >> rowbuf.exampleStr;   cols["DOUBLE_VALUE"] >> rowbuf.exampleDouble;   cols["EXAMPLE_LONG"] >> rowbuf.exampleLong;   cols["EXAMPLE_DATE"] >> rowbuf.exampleDate;}}
     感觉就是将一个函数功能写成了类,感觉可以看做重载()操作符(当然,这里面还重载了>>、<<、==三个操作符,重载果然厉害)

     关于为什么要引入函数对象,http://developer.51cto.com/art/201002/183522.htm 提出2个:一是,与函数指针相比,函数对象可以附带数据;二是函数对象可以封装类成员函数指针;函数对象之于函数指针的优势,也可以参考http://cpp.ezbty.org/content/science_doc/c%E6%A0%87%E5%87%86%E5%BA%93%EF%BC%9A%E5%87%BD%E6%95%B0%E5%AF%B9%E8%B1%A1,而 http://blog.csdn.net/roger_77/article/details/755613 则从函数指针的弱点提出,由于函数指针笨拙(其实已经很方便了)危险(这个倒是常提),所以函数对象的提出,很大部分,像是替代函数指针之用。关于STL中的函数对象,一个更详细的可以参考http://www.dutor.net/index.php/2010/04/stl-functor-function-object/ 另外http://feiqiang.iteye.com/blog/373914则是提出了不少经常用到的函数对象,像for_each(),实际上,以前看C++ STL范例大全也有如下示例

#include <iostream> #include <vector> #include <algorithm> using namespace std; template <class T> class Print { public:void operator () (T& t) { cout << t << " "; } }; int main () {vector<int> v(10); Print<int> print; fill(v.begin(),v.end(),5); cout << "Vector v : "; for_each(v.begin(),v.end(),print); cout << endl; cout << "Size of v = " << v.size() << endl; cout << "v.clear" << endl; v.clear();return 0;} 
    里面的Print不也是函数对象呢么?for_each()也是,for_each()什么的,不说书写方便了,估计性能也是很可观的,高级货啊。貌似侯捷翻译这个是仿函数?不得不说,这个更贴切啊,虽然Function Object直译也没什么,不过总不如仿字传神,大师就是大师啊。

       搜的过程顺便看到关于快速排序,stdlib.h的qsort()和algorithm的sort(),http://www.cnblogs.com/drizzlecrj/archive/2007/09/04/882120.html 提到的一个细节,是写compare函数的时候(这个目前见到的大多都是函数指针吧,虽然应该也可以用函数对象),需要注意溢出等异常情况(反正我是直接return a<b,问题不大)

       就这样吧,留之,有用