How to serialize a class with a boost::dynamic_bitset member?
#include
#include
dynamic_bitset<> is not serializable, as you've found out (std::bitset is different type).
Not to worry, though, you can add it without too much effort:
namespace boost { namespace serialization {
template
void save(Ar& ar, dynamic_bitset const& bs, unsigned) {
size_t num_bits = bs.size();
std::vector blocks(bs.num_blocks());
to_block_range(bs, blocks.begin());
ar & num_bits & blocks;
}
template
void load(Ar& ar, dynamic_bitset& bs, unsigned) {
size_t num_bits;
std::vector blocks;
ar & num_bits & blocks;
bs.resize(num_bits);
from_block_range(blocks.begin(), blocks.end(), bs);
bs.resize(num_bits);
}
template
void serialize(Ar& ar, dynamic_bitset& bs, unsigned version) {
split_free(ar, bs, version);
}
} }
This works e.g. Live On Coliru
int main() {
A a;
for (int i=0; i<128; ++i)
a.x.resize(11*i, i%2);
std::stringstream ss;
{
boost::archive::text_oarchive oa(ss);
oa << a;
}
std::cout << ss.str();
{
boost::archive::text_iarchive ia(ss);
A b;
ia >> b;
assert(a.x == b.x);
}
}
Note that if you can't afford to copy the blocks vector, it's equally easy to add serialization directly on the m_bits level, but that requires intrusive changes (friend access required at a minimum).
Such a thing would easily be added to boost in a pull request.