c++11 怎么序列化结构体?

2023 年 2 月 21 日
 bfjm
怎么在编译期知道结构体有哪些成员对象
3888 次点击
所在节点    C++
23 条回复
ugpu
2023 年 2 月 21 日
auto ptr = &struct
send_buff(&ptr, len(struct))

???? 类似这样 最基础的
bfjm
2023 年 2 月 21 日
@ugpu 怎么在编译期知道有哪些成员呢
ysc3839
2023 年 2 月 21 日
@bfjm 标准 C++没办法
bfjm
2023 年 2 月 21 日
@ysc3839 有文档讲怎么实现的也可以
bfjm
2023 年 2 月 21 日
@ysc3839 我找了几个标准都要 14 17 这种满办法满足
ugpu
2023 年 2 月 21 日
@bfjm 编译期知道有哪些成员?
那就需要自己做结构体特殊化 标识 了吧 纯使用标准库来说 没见到过.
bfjm
2023 年 2 月 21 日
有 protobuf 可以用 我在知乎上看评论 protobuf 可以实现反射 有人指路一下吗 具体一点
polythene
2023 年 2 月 21 日
编译期反射 14/17 都不支持吧,pb 能做到是因为它能从 IDL 文件里拿到字段的偏移量,而不是靠编译期反射吧
Jiavwen
2023 年 2 月 21 日
必然有个元数据记录 struct 中每个元素的首地址和偏移量啊
boboliu
2023 年 2 月 21 日
pb 是自己 IDL + codegen 来的
你要反射的话就只能自己组织元数据了,比如 https://github.com/netcan/recipes/blob/master/cpp/metaproggramming/reflection/StaticRefl.cpp
kevinlq
2023 年 2 月 21 日
建议先学习第三方库如何使用、再研究如何实现的,最后如果想自己造轮子再试着撸一个。

可以看看 protobuf ,msgpack 啊这些, 也可以看看 Qt 的元对象实现
GeruzoniAnsasu
2023 年 2 月 21 日
啊? 序列化结构体

boost::serialization
mingl0280
2023 年 2 月 22 日
结构体是 POD 的:头文件直接转 char 或者 unsigned char 。
非 POD 的:头文件+序列化 /反序列化函数
mingl0280
2023 年 2 月 22 日
要获取成员涉及到一些模板元编程的东西,你现在没必要研究这个
786375312123
2023 年 2 月 22 日
编译期知道结构体有哪些成员对象?
太难了,你连编译期间 enum 里有那些成员都没法弄清楚,还需要写一个标记开头结尾。
就这么看编译期间想知道类里有什么根本做不到,除非这个类是模板类?模板类能做到么?我没试过。
xy629
2023 年 2 月 22 日
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <cstdlib>
#include <stdexcept>

#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>

struct MyStruct
{
int i;
double d;
std::string s;

// 序列化成文本格式
template <class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & i;
ar & d;
ar & s;
}
};

int main()
{
// 将结构体序列化为二进制格式并写入文件
{
MyStruct s{42, 3.14, "hello world"};
std::ofstream ofs("data.bin", std::ios::binary);
boost::archive::binary_oarchive oa(ofs);
oa << s;
}

// 从文件中读取二进制数据并反序列化为结构体
{
MyStruct s;
std::ifstream ifs("data.bin", std::ios::binary);
boost::archive::binary_iarchive ia(ifs);
ia >> s;

// 验证反序列化结果是否正确
if (s.i != 42 || s.d != 3.14 || s.s != "hello world")
{
throw std::runtime_error("Deserialization failed");
}
}

return 0;
}
AlohaV2
2023 年 2 月 22 日
感觉可以看一下 protobuf
blinue
2023 年 2 月 22 日
不追求安全性的话可以看一下 https://github.com/niXman/yas
最大的优点是唯头文件,速度也很快。
bfjm
2023 年 2 月 23 日
用 boost 的序列化库解决了
bfjm
2023 年 2 月 23 日
@xy629 thank you ,我最后也是差不多这种

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://study.congcong.us/t/918040

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX