I wrote a little ‘lazy vector’ class (or, delayed vector) which is supposed to look like a std::vector and usable wherever a std::vector is used, but it loads its elements ‘lazily’, i.e. it will load element n (and possibly a few more) from disk whenever someone accesses element n. (The reason is that in my app, not all elements fit into memory.)
Here is this LazyVector class, but there is a problem with const member functions that use such a vector, see below.
template<class T> class LazyVector { std::vector<T> elems_; void fetchElem(unsigned n){ // load the n-th elem from disk into elems_ etc } public: const T& operator[](unsigned n) const { fetchElem(n); // ERROR: ... discards qualifiers return elems_[n]; } T& operator[](unsigned n) { fetchElem(n); return elems_[n]; } // and provide some other std::vector functions };
As I said, there is a problem when a const member function asks for an element of the LazyVector. By nature of the LazyVector, accessing an element is not const, i.e. it will change the vector vec below, which is forbidden in this context. The foo member function must be const and cannot be changed. How can I solve this?
class Foo { LazyVector<const std::string*> vec; void fct(int n) const { // fct must be const const std::string* str = vec[n]; // do something with str } };
You can either use mutable member data or const_cast in the implementation of your LazyVector class. Thus you can create the illusion of constness needed by your consuming class without actually being const.