Boost logo

Boost :

From: Peng Yu (pengyu.ut_at_[hidden])
Date: 2008-07-10 02:24:34


Hi,

The following program uses virtual functions. Essentially I need to go
through all the pairs in 'v'.

Since I have already know what are in v at compile time. I would like
to convert the dynamic polymorphism to template. Therefore, the
runtime would be better. I think this should be done with the help of
boost::mpl. But I'm not sure how to do it. Would you please help me?

Thanks,
Peng

#include <iostream>
#include <vector>
#include <boost/shared_ptr.hpp>

struct shape {
  virtual void show_me() const = 0;
  virtual ~shape() { }
};

struct square : public shape {
  void show_me() const {
    std::cout << "square";
  }
};

struct circle : public shape {
  void show_me() const {
    std::cout << "circle";
  }
};

struct triangle : public shape {
  void show_me() const {
    std::cout << "triangle";
  }
};

int main() {
  std::vector<boost::shared_ptr<shape> > v;
  {
    boost::shared_ptr<shape> s(new square);
    v.push_back(s);
  }
  {
    boost::shared_ptr<shape> s(new circle);
    v.push_back(s);
  }
  {
    boost::shared_ptr<shape> s(new square);
    v.push_back(s);
  }
  {
    boost::shared_ptr<shape> s(new triangle);
    v.push_back(s);
  }

  for(std::vector<boost::shared_ptr<shape> >::const_iterator it =
v.begin(); it != v.end(); ++ it) {
    for(std::vector<boost::shared_ptr<shape> >::const_iterator it2 =
it + 1; it2 != v.end(); ++ it2) {
      (*it)->show_me();
      std::cout << " vs. ";
      (*it2)->show_me();
      std::cout << std::endl;
    }
  }
}


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk