Search code examples
c++c++11iteratorconstantsauto

Why doesn't const range based for use const_iterator?


If I only want to expose a const iterator to by object:

class MyList
{
  public:
    const_iterator begin() const;
    const_iterator end() const;
  private:
    iterator begin();
    iterator end();
};

it seems I should be able to use a const version of the range based for:

MyList list;
...
for(const auto & value : list)
{
}

The compiler complains that begin and end are private. Why doesn't it use the const_iterator versions?


Solution

  • Overload resolution is done before access-checking, to avoid magically breaking code just by changing access-specifiers.

    What happens to the expression afterwards (its type) is disregarded for that. If needed, the compiler will try to find a valid and unambiguous conversion-sequence afterwards instead.

    Thus, the begin and end for a non-const-object are selected, and then the compiler stumbles over that big private-sign.