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

标签 c++ storage containers

是否有任何结构、类或容器可以用来存储可序列化的异构项目。例如,假设我有一个 int、float 和另一个类对象。我想在运行时将它们全部存储在特定的容器中,并将其跨类传递。 C++ 是否提供任何此类选项。

最佳答案

您可以使用 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;
}

关于c++ - C++ 中用于存储异构项的类或容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3475317/

相关文章:

c# - 在 .NET 中存储常量值的最佳方式

java - 无法保存使用应用程序拍摄的图像?

ios - 如何使用 NSURLIsExcludedFromBackupKey 或 kCFURLIsExcludedFromBackupKey?

containers - 访问英国数据中心的 IBM Containers 时出现问题

带有对象的 Qt 容器

c++ - 与 C++ 中的 numpy.random.choice 等效的函数

c++ - 如何编写一个返回其子函数返回类型的函数

c++ - 以编程方式检查字节顺序

c++ - OpenCV 中的支持 vector 机 : low accuracy OCR with RBF kernel

kubernetes - GKE- sudo docker ps 在部署运行时不返回任何内容