无我

让内心永远燃烧着伟大的光明的精神之火!
灵活的思考,严谨的实现
豪迈的气魄、顽强的意志和周全的思考

【转】C++中的function object

看过了funciton object中的部分内容,感觉这些技术、 概念等真的需要慢慢体会,才能感受到它的博大精深。

看下面的这个例子:

  #include <iostream>
   #include <vector>
   #include <algorithm>
   using namespace std;
 void printInt (int elem)
   {
       cout << elem << ' ' ;
   }

   int main()
   {
       vector<int> coll;

       //insert elements from 1 to 9
       for (int i=1; i<=9; ++i) {
           coll.push_back(i);
       }

       //print all elements
       for_each (coll.begin(), coll.end(),printInt);            
       cout << endl;
   }

对于这个例子,for_each()的第三个参数,调用了printInt这个函数。在看下面的例子:

#include <iostream>
   #include <vector>
   #include <algorithm>
   using namespace std;

   //simple function object that prints the passed argument
   class PrintInt {
     public:
       void operator() (int elem) const {
           cout << elem << ' ';
       }
   };

   int main()
   {
       vector<int> coll;
       //insert elements from 1 to 9
       for (int i=1; i<=9; ++i) {
           coll.push_back(i);
       }

       //print all elements
       for_each (coll.begin(), coll.end(),    PrintInt()); 

       cout << endl;
   }

在这个例子中,for_each()的第三个参数就是函数对象。

那么这到底有什么区别呢?也许从上面的代码中还看不出,但是,请继续看下面的例子:

//对每一个element加10;

void add10 (int& elem)
   {
       elem += 10;
   }

   void fl()
   {
       vector<int> coll;
       ...

       for_each (coll.begin(), coll.end(),   add10);                   
   }
这样看起来似乎很好,但是,如果突然要求变了,要求对每一个element改成加9;那么,可能想到的办法是改写函数

void add9 (int& elem)
   {
       elem +=9;
   }

哦,那么要求又改成+8、+7…… -3等等,总不至于对于每一个都重新写一个函数吧?虽然可行,但是违背

范型变成的思想。也许有新的办法:

template <int theValue>
   void add (int& elem)
   {
       elem += theValue;
   }

void f1()
   {
       vector<int> coll;
       ...

       for_each (coll.begin() , coll.end(),     //range
                 add<10>);                      //operation
   }
但是,如果连类型(int)都变了(如改成float),那该怎么实现呢?哦,用一般的函数应该不能实现了吧?

但是如果用function object思想,就可以实现,看下面的代码:

template <class T>

class AddValue {
      private:
        T theValue;     

       public:
            AddValue(T v) : theValue(v) {
        }

            void operator() (T& elem) const {
            elem += theValue;
        }
   };
现在这个类就可以实现多个类型的相加形式了。

因此可以总结在用函数对象时,可以更加满足了STL的范型编程思想。

posted on 2007-10-15 10:36 Tim 阅读(1524) 评论(0)  编辑 收藏 引用 所属分类: C/C++语言


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2014年5月>
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567

导航

统计

公告

本博客原创文章,欢迎转载和交流。不过请注明以下信息:
作者:TimWu
邮箱:timfly@yeah.net
来源:www.cppblog.com/Tim
感谢您对我的支持!

留言簿(9)

随笔分类(173)

IT

Life

搜索

积分与排名

最新随笔

最新评论

阅读排行榜