0

I am trying to implement bitset operators on a vector< bool> wrapper class.

My question is why the subscript operator [] works when the vector is an int, but not when it's a bool.

struct bitsetI {
    vector<int> data;
    bitset(int length) { data = vector<int>(length);}
    int &operator[](const int index) { return data[index]; }
}

struct bitsetB {
    vector<bool> data;
    bitset(int length) { data = vector<bool>(length);}
    bool &operator[](const int index) { return data[index]; }
}

With bitsetI

bitsetI I(4);
I[0] = 1;

is valid, but

bitsetB B(4);
B[0] = true;

won't compile, giving an "initial value of reference to non-const must be an lvalue" error.

I know that vector is an awkward specialization of vector (implementing this because I need to be able to declare bitstring lengths at runtime, not compile as with std::bitset, and speed is not an issue), but can't figure out what the problem is here, and if there's a work-around or if I should just use a set function instead.

Nicholas McCarthy
  • 346
  • 1
  • 6
  • 15

0 Answers0