gpt4 book ai didi

c++ - c++17如何获取 "any"存储的数据大小?

转载 作者:太空宇宙 更新时间:2023-11-04 14:52:22 25 4
gpt4 key购买 nike

假设我有这样一个函数

int writetofile(wstring name, any sdata){
...
return error;
}

此函数不知道将存储什么数据,但需要知道存储在 sdata 中的数据的大小。虽然很容易确定 sdata 中存储的数据类型,但我认为没有什么简单的方法可以了解 sdata 中数据的大小。


我有一个数据结构,其成员类型为wstring。现在我们不能将该数据结构直接写入文件,因为它包含该 wstring。就我在互联网上的研究而言,编写 wstringstring 的最佳方法是先写字符串的大小,然后再写字符串。然后,当我读取字符串时,首先读取大小,然后再读取那么大的大小。

为此我做了一个函数。

int filemanager::write(any data, fileid uid, DWORD *byteswritten) const
{
// files is a map<fileid, fileinfo> where fileinfo is a struct which has
// members including file's name and handle
// fileid is a typedef of int
if (!files.count(uid)) return -1;
if (!data.has_value()) return -2;
if (data.type() == typeid(wstring)) {
DWORD sz1, sz2;
wstring str = any_cast<wstring>(data);
size_t sz3 = str.length()*sizeof(wchar_t);
if (sz3 == 0) return -2;
if (FALSE == WriteFile(files[uid].handle, &sz3, sizeof(size_t), &sz1, NULL)){
return GetLastError();
}
if (FALSE == WriteFile(files[uid].handle, str.c_str(), sz3, &sz2, NULL) && sz2 != sz3) {
return GetLastError();
}
if (byteswritten != nullptr) *byteswritten = sz1 + sz2;
}
else {
// now if the type is not a wstring then just write it to a file
// here i would need the size of the data stored in the data
}
return 0;
}

最佳答案

std::any 不是您要执行的操作的正确工具。它是一个主要用于 A 点和 B 点之间通信的工具,其中 两点 都知道类型是什么,但是通信需要通过一些不需要知道类型的中间代码 C 进行.

如果 B 需要尝试一系列不同的转换来查看提供了哪个值,any 不是完成这项工作的正确工具。强制转换是出于类型安全的原因:在提供错误的 any 的情况下有一个明确定义的故障路径。也就是说,要确保 A 和 B 正确通信。它不在那里,所以你可以尝试一堆不同的东西。

你不能问 any 存储对象的大小是多少,因为你应该已经知道答案了。即使您不知道答案,您也永远无法有效使用该答案。

以您的用例为例。 any 不是 TriviallyCopyable,因此 不是 合法的 C++ 将其字节直接复制到文件然后再将它们复制回来。即使这样做在概念上是可行的,any 也可能只存储指向它包含的对象的指针。因此,您只需编写一个指向该文件的指针。

C++ 中的序列化不会像您想的那样简单。

关于c++ - c++17如何获取 "any"存储的数据大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51882028/

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