Is cbegin / cend insufficient for loop based range?

I have a class, let's call it ConstVector, which defines cbegin / cend, not begin / end, because I don’t want to allow modification of its elements after construction. I tried using a loop based range like this:

ConstVector const_vector(1, 2, 3); for(const auto &x : const_vector) .... 

So far, the relevant part of the class looks like this:

 template<class T> class ConstVector { public: ConstVector(std::initializer_list<T> values); typename std::vector<T>::const_iterator cbegin(void) const; typename std::vector<T>::const_iterator cend(void) const; private: std::vector<T> data; }; template<class T> ConstVector::ConstVector(std::initializer_list<T> values) : data(values) { } template<class T> typename std::vector<T>::const_iterator ConstVector<T>::cbegin() const { return this->data.cbegin(); } template<class T> typename std::vector<T>::const_iterator ConstVector<T>::cend() const { return this->data.cend(); } 

But my compiler complains:

 'begin' was not declared in this scope 

My question is: do I need to start / end? As I understand it, it should select cbegin / cend if it is const auto &x and not auto &x . At least that would make sense to me. If I remove my loop based range, everything compiles fine.

I also tried almost everything that was suggested here to make it const , but that didn't help.

+8
c ++
source share
1 answer

Do I need to start / end?

Yes.

As I understand it, it should select cbegin/cend if it is const auto &x and not auto &x .

This is not how the standard defines for based on a range. Based on the range, the for always searches for begin() and end() . From https://timsong-cpp.imtqy.com/cppwp/n3337/stmt.ranged .

otherwise, begin-expr and end-expr are equal to begin(__range) and end(__range) respectively, where begin and end looked up with a search argument ([basic.lookup.argdep]). For the purpose of finding this name, the std namespace is an associated namespace.

+8
source share

All Articles