Boost.Bind和Boost.Function的一种搭配使用法

时间:2023-01-24 04:38:45

http://blog.sina.com.cn/s/blog_4b3dfc920100kfdp.html


昨天在CSDN上看到一篇文章,说是用Boost.Bind和Boost.Function可以完全取代继承,大致浏览了一下觉得还是很有意思的,于是自己动手试了一下~不过由于没有仔细研读文章,所以不知道自己的设想是否跟作者的意思一致,呵呵~

   举个在演示多态时被用过很多遍的例子:
   class Shape
   {
    pubilc:
      virtual void draw() = 0;
   };
    
   class Rect : public Shape
   {
    public:
      Rect(const string& nm) : name(nm) {}
 
      virtual void draw() {
         cout << "Rect:" << name << '\n';
      }
    private:
      string name;
   };
 
   class Circle : public Shape
   {
    public:
      Circle(const string& nm) : name(nm) {}
 
      virtual void draw() {
         cout << "Circle:" << name << '\n';
      }
    private:
      string name;   
   };
 
   vector<Shape*> vpShape;
   vpShape.push_back(new Rect("First"));
   vpShape.push_back(new Circle("Second"));
 
   for_each(vpShape.begin(), vpShape.end(), mem_fun(&Shape::draw));
   输出结果为:
   Rect:First
   Circle:Second
 
   这就是继承下的多态了~现在使用Boost.Bind和Boost.Function达到同样的效果:
   class Shape
   {
       typedef boost::function<void ()> Fun;
    public:
       Shape(Fun f) : fun(f) {}
 
       void draw() {
           fun();
       }
    private:
       Fun fun;
   };
 
   class Rect
   {
    public:
       typedef void result_type;
         
       result_type operator()(const string& name) {
           cout << "Rect:" << name << '\n';
       }
   };
 
   class Circle
   {
    public:
        typedef void result_type;
          
        result_type operator()(const string& name) {
            cout << "Circle:" << name << '\n';
        }
   };
 
   vector<Shape> vShape;
   vShape.push_back(Shape(boost::bind(Rect(), "First")));
   vShape.push_back(Shape(boost::bind(Circle(), "Second")));
 
   for_each(vShape.begin(), vShape.end(), boost::bind(&Shape::draw, _1));
   输出结果跟上面继承的例子是一样的~
    
   基本上每本讲面向对象程序设计的书都会告诫读者不要过多使用继承,还提供了一些判断是否应该使用继承的经验原则,但继承肯定是有其合理性的,关键在于是否运用得适当和有效。用Boost.Bind和Boost.Function确实降低了继承在效率上的开销,但我觉得并不能完全取代继承,呵呵~