我还找不到任何有关如何将unique_ptr序列化为数组的文档。任何帮助都会很棒。
struct Counter{
int index;
unique_ptr<char []> name;
template<class Archive>
void serialize(Archive & archive){
archive(index, name ); // serialize things by passing them to the archive
}
};
如何分配。
auto buffer = std::unique_ptr<char[]>(new char[BUFFER_SIZE]);
instance.name = std::move(buffer);
答案 0 :(得分:0)
您可以执行此操作,但需要做一些额外的工作。根据存档类型的不同而不同。
对于基于文本的存档(例如XMLOutputArchive
/ XMLInputArchive
和JSONOutputArchive
/ JSONInputArchive
),您可以使用saveBinaryValue()
/ loadBinaryValue()
(http://uscilab.github.io/cereal/assets/doxygen/classcereal_1_1JSONOutputArchive.html)。
这是一个完整的例子:
#include <iostream>
#include <memory>
#include <cereal/archives/xml.hpp>
#include <cereal/cereal.hpp>
struct Counter
{
static constexpr std::size_t BUFFER_SIZE = 12;
int index{};
std::unique_ptr<char[]> name;
Counter() = default;
Counter(int i)
: index{i},
name{new char[BUFFER_SIZE]}
{}
template<class Archive>
void load(Archive& archive)
{
archive(index);
name.reset(new char[BUFFER_SIZE]);
archive.loadBinaryValue(name.get(), BUFFER_SIZE * sizeof(decltype(name[0])));
}
template<class Archive>
void save(Archive& archive) const
{
archive(index);
archive.saveBinaryValue(name.get(), BUFFER_SIZE * sizeof(decltype(name[0])));
}
};
int main()
{
cereal::XMLOutputArchive archive(std::cout);
Counter c(42);
archive(CEREAL_NVP(c));
}
如果您使用的是BinaryOutputArchive
/ BinaryInputArchive
或PortableBinaryOutputArchive
/ PortableBinaryInputArchive
,则功能将变为saveBinary()
和loadBinary()
(http://uscilab.github.io/cereal/assets/doxygen/classcereal_1_1PortableBinaryOutputArchive.html )。
对于这些,您还可以使用binary_data()
包装数组:
template<class Archive>
void save(Archive& archive) const
{
archive(index, cereal::binary_data(name.get(), BUFFER_SIZE));
}