用于在C ++中存储异构项的类或容器

时间:2010-08-13 08:56:22

标签: c++ storage containers

是否有任何结构或类或容器可用于存储可序列化的异类项目。例如,假设我有一个int,float和另一个类对象。我希望在运行时将所有这些存储在特定容器中,并将其传递给各个类。 C ++是否提供任何此类选项。

1 个答案:

答案 0 :(得分:5)

您可以使用vector of boost::variant,例如

#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;
}