#include <iostream>
#include <string>
int main() {
using std::string;
using std::distance;
using std::cout;
using std::endl;
string s("abc");
string::const_iterator b = s.begin();
string::const_iterator e = s.end(); // success
cout << distance(b, e) << endl;
cout << distance(b, static_cast<string::const_iterator>(s.end())) << endl;
cout << distance(b, s.end()) << endl; // error
return 0;
}
End of the string s.end()
can be implicitly converted to std::string::const_iterator
as e
, but when it is passed as function parameter, it has to be explicitly casted; otherwise an error is raised in compile time. Why is that?
FYI, s.begin()
and s.end()
both seem to return std::string::iterator
.
An expression
e
is said to be implicitly convertible toT2
if and only ifT2
can be copy-initialized frome
, that is the declarationT2 t = e;
is well-formed (can be compiled), for some invented temporaryt
.
The function has one template parameter
So it can not deduce the type of the template parameter because either iterator const or non-const can be used for each function parameter.
You could write without casting the following way
explicitly specifying the template argument.
Another example. This code snippet also will not compile
However if you will write
then the code compiles.