你可以做到,但它需要一些额外的工作。它因存档的类型而异。
对于基于文本的档案(例如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));
}