Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 206
Alec Jacobson Avatar asked Oct 24 '14 19:10

Alec Jacobson


1 Answers

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.

like image 197
Deduplicator Avatar answered Nov 12 '22 15:11

Deduplicator