通过运算符[]按位操作

时间:2016-01-13 11:48:04

标签: c++11 bit-manipulation bitwise-operators

我正在编写一个简单的bitset包装器,以便从8位整数中轻松有效地设置清除读取位。我会通过operator[]进行这三项操作,但是我很沮丧,说实话,我不确定这是否可能不会失去表现(对我的目的来说非常重要)。

#include <stdint.h>
#include <iostream>

class BitMask {
private:
    uint8_t mask;
public:
    inline void set(int bit) { mask |= 1 << bit; } // deprecated
    inline void clear(int bit) { mask &= ~(1 << bit); } // deprecated
    inline int read(int bit) { return (mask >> bit) & 1; } // deprecated
    bool operator[](int bit) const { return (mask >> bit) & 1; } // new way to read
    ??? // new way to write
    friend std::ostream& operator<<(std::ostream& os, const BitMask& bitmask) {
        for (int bit = 0; bit < 8; ++bit)
             os << ((bitmask.mask >> bit) & 1 ? "1" : "0");
        return os;
    }
};

int main() {
    BitMask bitmask1;
    bitmask1.set(3);
    bitmask1.clear(3);
    bitmask1.read(3);
    std::cout << bitmask1;

    BitMask bitmask2;
    bitmask2[3] = 1; // set
    bitmask2[3] = 0; // clear
    bitmask2[3]; // read
    std::cout << bitmask2;
}

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

一种方法(唯一的方法是?)是从operator[]返回一个代理对象,它将为你的位保留索引,这样你就可以为代理对象分配新值,这将改变相应的BitMask位。例如,请参见此处:Vector, proxy class and dot operator in C++

至于性能 - 这完全取决于编译器如何优化您的代码,如果您的代理类只有内联方法,那么它应该很快。

以下是如何修复代码的示例:

#include <stdint.h>
#include <iostream>

class BitMask {
private:
  uint8_t mask;
public:
  inline void set(int bit) { mask |= 1 << bit; } // deprecated
  inline void clear(int bit) { mask &= ~(1 << bit); } // deprecated
  inline int read(int bit) const { return (mask >> bit) & 1; } // deprecated

  struct proxy_bit
  {
    BitMask& bitmask;
    int index;
    proxy_bit(BitMask& p_bitmask, int p_index) : bitmask(p_bitmask), index(p_index) {}
    proxy_bit& operator=(int rhs) {
      if (rhs)
        bitmask.set(index);
      else
        bitmask.clear(index);
      return *this;
    }
    operator int() {
      return bitmask.read(index);
    }
  };

  proxy_bit operator[](int bit) { return proxy_bit(*this, bit); } // new way to read
  int operator[](int bit) const { return read(bit); } // new way to read

  friend std::ostream& operator<<(std::ostream& os, const BitMask& bitmask) {
    for (int bit = 0; bit < 8; ++bit)
      os << ((bitmask.mask >> bit) & 1 ? "1" : "0");
    return os;
  }
};

int main() {
  BitMask bitmask1;
  bitmask1.set(3);
  bitmask1.clear(3);
  bitmask1.read(3);
  std::cout << bitmask1 << std::endl;

  BitMask bitmask2;
  bitmask2[3] = 1; // set
  bitmask2[3] = 0; // clear
  bitmask2[3]; // read
  std::cout << bitmask2 << std::endl;

  const BitMask bitmask3;
  if (bitmask3[3]) {}
  //bitmask3[3] = 1; // compile error - OK!
}