|
Boost Users : |
From: Roman Perepelitsa (roman.perepelitsa_at_[hidden])
Date: 2008-07-10 08:01:58
Peng Yu <pengyu.ut <at> gmail.com> writes:
>
> 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?
You can use boost::fusion::vector (or boost::tuple) as a
container. You can use boost::fusion::for_each to iterate
through it (there are other algorithms in fusion of course).
#include <iostream>
#include <boost/fusion/container/vector.hpp>
#include <boost/fusion/algorithm/iteration/for_each.hpp>
struct square {
void show_me() const {
std::cout << "square\n";
}
};
struct circle {
void show_me() const {
std::cout << "circle\n";
}
};
struct triangle {
void show_me() const {
std::cout << "triangle\n";
}
};
struct show {
template <class T>
void operator()(const T& obj) const {
obj.show_me();
}
};
int main() {
using namespace boost::fusion;
vector<square, circle, triangle, square> v;
for_each(v, show());
}
HTH,
Roman Perepelitsa.
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