Is there any structure or class or container which i can use to store heterogenous items which is serializable. For example say i have a int,float and another class object. I want to store all of them in a particular container at runtime and pass it across classes. Does C++ give any such options.
+3
A:
You could use a vector
of boost::variant
, e.g.
#include <boost/serialization/vector.hpp>
#include <boost/serialization/variant.hpp>
// note: the above are serializable variants of
// #include <vector>
// #include <boost/variant.hpp>
#include <fstream>
#include <iostream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <algorithm>
#include <iterator>
struct Point {
float x, y;
Point(float x_, float y_) : x(x_), y(y_) {}
Point() : x(0), y(0) {}
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version) {
ar & x;
ar & y;
}
};
std::ostream& operator<< (std::ostream& o, const Point& p) {
return o << "{x:" << p.x << ", y:" << p.y << "}";
}
int main () {
std::vector<boost::variant<int, float, Point> > vec;
vec.push_back(12345);
vec.push_back(0.65432f);
vec.push_back(Point(2.5, 6.7));
{
std::ofstream f("1.txt");
{
boost::archive::text_oarchive serializer(f);
serializer << vec;
}
}
{
std::ifstream f("1.txt");
{
std::vector<boost::variant<int, float, Point> > result;
boost::archive::text_iarchive deserializer(f);
deserializer >> result;
std::copy(result.begin(), result.end(),
std::ostream_iterator<boost::variant<int, float, Point> >(std::cout, "\n"));
}
}
return 0;
}
KennyTM
2010-08-13 08:58:40