Why does the following code compile for the line using a non-const iterator but fails for the const iterator (using Visual Studio 2008) ?
#include <vector>
using std::vector;
int main(int argc, char* argv[])
{
vector<int> test;
test.push_back(1);
test.push_back(2);
vector<int>::const_iterator cit = test.end();
std::distance(test.begin(), cit); // error: template parameter is ambiguous
vector<int>::iterator it = test.end();
std::distance(test.begin(), it);
return 0;
}
Note: In Visual Studio 2008 there is no vector member function cbegin() to avoid the ambiguousness, but an overloaded begin() method:
iterator begin()
{ // return iterator for beginning of mutable sequence
return (iterator(_Myfirst, this));
}
const_iterator begin() const
{ // return iterator for beginning of nonmutable sequence
return (const_iterator(_Myfirst, this));
}
I think the compiler always picks the non-const overload for a non-const objects, and the const method only for const objects.
Calling
doesn’t look at the overload set for
beginand the type ofcit, and figure out whether it can make a match. It resolves the overload first (to the non-const version), and hence fails.The cleanest way to express your intent that will also work for the compiler is probably: