#include namespace mpi = boost::mpi; #include #include #include #include #include struct Base { std::string msg_; Base(std::string msg) : msg_(msg) { }; Base() : msg_() { }; // default ctor needed for serialization virtual ~Base() { }; virtual void greet(std::ostream& out) const { out << "A base greeting: " < msg_ << std::endl; }; template void serialize(Archive& ar, const unsigned int version) { ar & msg_; }; }; struct Derived1 : public Base { Derived1(std::string msg) : Base(msg) { }; Derived1() : Base() { }; virtual void greet(std::ostream& out) const { out << "A first derived greeting: " << this->Base::msg_ << std::endl; }; }; struct Derived2 : public Base { Derived2(std::string msg) : Base(msg) { }; Derived2() : Base() { }; virtual void greet(std::ostream& out) const { out << "Another derived greeting: " << this->Base::msg_ << std::endl; }; }; typedef boost::variant my_variant_t; struct do_greet: public boost::static_visitor<> { template void operator()(const T& t) const { t.greet(std::cout); }; }; int main(int argc, char** argv) { mpi::environment env(argc, argv); mpi::communicator world; const int me = world.rank(); const int np = world.size(); std::cout << "rank " << me << " of " << np << " starting..." << std::endl; for (int i = 0; i < 10; ++i) { const int root = i % np; my_variant_t v; if (me == root) { std::ostringstream ostr; ostr << "message no." << i << " from rank " << me; switch (i % 3) { case 0: { Base c(ostr.str()); v = c; break; }; case 1: { Derived1 c(ostr.str()); v = c; break; }; case 2: { Derived2 c(ostr.str()); v = c; break; }; }; }; mpi::broadcast(world, v, root); std::cout << "rank " << me << ": "; boost::apply_visitor(do_greet(), v); std::cout << std::endl; }; return 0; };