c++boostboost-dynamic-bitset

Error using boost::from_block_range on member dynamic_bitset, but not on local dynamic_bitset


I am attempting to convert a std::vector<uint8_t> into a boost::dynamic_bitset. I can achieve the inverse of this using the following code, where values is a class member function defined as boost::dynamic_bitset<uint8_t> values.

std::vector<uint8_t> payload;
boost::to_block_range(values, std::back_inserter(payload));

However, I can't figure out how to do the inverse of it. The following compiles:

void MyClass::decode(std::vector<uint8_t> payload) const
{
    boost::dynamic_bitset<uint8_t> bits(payload.size() * 8);
    boost::from_block_range(payload.begin(), payload.end(), bits);
}

If I replace the bits local scoped-variable with the values class member variable (which from all indications are the same exact type, boost::dynamic_bitset<uint8_t>), I get the following compiler error:

error: no matching function for call to ‘from_block_range(std::vector<unsigned char>::iterator, std::vector<unsigned char>::iterator, const boost::dynamic_bitset<unsigned char>&)’ boost::from_block_range(payload.begin(), payload.end(), values);


Solution

  • Your decode method is marked const, but you are attempting to modify class member variable values.

    Either remove the const or mark values mutable

    For example:

    #include <cstdint>
    #include <vector>
    #include "boost/dynamic_bitset.hpp"
    
    struct foo
    {
        void do_the_thing()
        {
            std::vector<uint8_t> payload{1, 2, 3, 4};
            bits = boost::dynamic_bitset<uint8_t>(payload.size() * 8);
            boost::from_block_range(payload.begin(), payload.end(), bits);
        }
        
        boost::dynamic_bitset<uint8_t> bits;
    };
    
    int main()
    {
        foo f;
        f.do_the_thing();
    }