Boost logo

Boost Users :

From: Igor R (boost.lists_at_[hidden])
Date: 2008-07-10 07:26:05


Do you mean you want your vector to be heterogenous, i.e. containing
different types?
If so, you can use boost::variant:

typedef boost::variant<square, circle, triangle> shape_type; //
square, circle, triangle may be unrelated types providing show_me()
method
std::vector<shape_type> shapes;
struct drawer : boost::static_visitor<>
{
  template<typename shape> void operator()(shape &sh) const
  {
    sh.show_me();
  }
};

int main()
{
  shapes.push_back(triangle());
  shapes.push_back(circle());
  BOOST_FOREACH(std::vector<shape_type>::reference shape, shapes)
    boost::apply_visitor(drawer(), shape);
}

2008/7/10, Peng Yu <pengyu.ut_at_[hidden]>:
> 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-users mailing list
> Boost-users_at_[hidden]
> http://lists.boost.org/mailman/listinfo.cgi/boost-users
>


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net