How to serialize boost::dynamic_bitset?

后端 未结 2 963
南旧
南旧 2020-12-06 14:17

How to serialize a class with a boost::dynamic_bitset member?

#include 
#include 

        
2条回答
  •  盖世英雄少女心
    2020-12-06 14:39

    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.

    Update added that pull request

提交回复
热议问题