如何使operator []返回对unsigned int中各个位的引用?

pig*_*lin 0 c++ bit-manipulation reference vector operator-keyword

我正在vector<bool>实施.我保存一个unsigned int并使用按位运算来得到一个true和false的向量.我的问题是这个; 我可以通过operator []访问各个位,但是如何获得对这样的位的引用以便我可以写入

Vector<bool> v(5, true);
v[3] = false;
Run Code Online (Sandbox Code Playgroud)

在某处我听说你不应该对各个位做引用/指针.代码摘要,适用于检索位值:

...
unsigned int arr;       // Store bits as unsigned int
unsigned int size_vec;  // The size of "bool vector"
...

bool& Vector<bool>::operator[](unsigned int i) {
 if (i>=vec_size || i<0) {
    throw out_of_range("Vector<bool>::operator[]");
 }
 int index = 1 << (i-1);
 bool n = false;
 if (index & arr) {
     n=true;
 }
 return n;
};
Run Code Online (Sandbox Code Playgroud)

那么,如何才能返回某种参考,从而可以改变各个位?

Pet*_*der 7

您需要使用适当的运算符重载来定义代理对象,以使其像bool&单个位一样工作.这是做什么的std::vector<bool>.

像这样的东西:

struct Bit
{
public:
    typedef unsigned char byte;

    Bit(byte& _byte, byte _bit)
    : m_byte(_byte), m_mask(1u << _bit)
    {}

    operator bool() const
    {
        return m_byte & m_mask;
    }

    Bit& operator=(bool x)
    {
        m_byte = x ? m_byte | m_mask : m_byte & ~m_mask;
        return *this;
    }

private:
    byte& m_byte;
    const byte m_mask;
};
Run Code Online (Sandbox Code Playgroud)

一般来说,我会建议避免这样的事情依赖于用C偷偷摸摸的隐式转换++,因为它真的与你的直觉食堂,和它不一样的东西发挥很好auto,并decltype在C++ 11.