mardi 22 septembre 2015

Override std::swap for Proxy classes c++

I've been assigned to implement a vector<bool> class with custom random access iterators, representing each bool as a bit in a unsigned int array. I'm using a proxy class, which has a pointer to a unsigned int and a index variable saying which bit is being modified.

So my vector<bool>s operator[] looks like:

BoolVectorProxy operator[](std::size_t index) {
    validate_bounds(index);
    return BoolVectorProxy(&array[index / BLOCK_CAPACITY], index % BLOCK_CAPACITY);
}

So far so good - however what happens when we need to, on the iterators ( which also returns BoolVectorProxy on the brackets operator and dereference operator), do some swapping?

This code does not compile:

Vector<bool> a({true, false});
std::swap(a[0], a[1]);
std::cout << a[0] << " " << a[1] << std::endl;

It should print 0 1 obviously but the less-than-pleasant error message says that I can't initialize a non-const reference of type BoolVectorProxy& from an rvalue of type BoolVectorProxy. The error is understandable - it tries to use the default std::swap but can't cast my returned rvalue to a reference.

How does one solve this?

Thanks,

Johan

Aucun commentaire:

Enregistrer un commentaire