函数参数隐式转换失败

implicit conversion fails in function parameter

#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;
}

字符串的结尾s.end()可以是implicitly convertedstd::string::const_iteratore,但是作为函数参数传递时,必须显式转换;否则会在编译时引发错误。这是为什么?

仅供参考,s.begin()s.end() 似乎都 return std::string::iterator

An expression e is said to be implicitly convertible to T2 if and only if T2 can be copy-initialized from e, that is the declaration T2 t = e; is well-formed (can be compiled), for some invented temporary t.

模板函数参数未转换。 std::distance 的两个参数必须是同一类型。

函数有一个模板参数

template <class InputIterator> 
typename iterator_traits<InputIterator>::difference_type 
distance(InputIterator first, InputIterator last); 

所以它无法推断模板参数的类型,因为迭代器 const 或非常量都可以用于每个函数参数。

你可以不强制转换就写成下面的方式

std::distance<std::string::const_iterator>(b, s.end()) 

明确指定模板参数。

再举个例子。此代码片段也不会编译

long x = 0;
int y = 0;
std::min(x, y);

但是如果你会写

long x = 0;
int y = 0;
std::min<long>(x, y);

然后代码编译。