gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 00:47:47 25 4
gpt4 key购买 nike

是否有任何结构、类或容器可用于存储可序列化的异构项目。例如说我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com