c++ - 函数参数隐式转换失败

标签 c++ parameters implicit-conversion 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() 似乎都返回 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.

最佳答案

函数有一个模板参数

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);

然后代码编译。

关于c++ - 函数参数隐式转换失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41474232/

相关文章:

c++ - for 循环中迭代器函数 next() 与 advance() 的性能

c++ - 这个 pow() 函数在 while 循环 C++ 中发生了什么?

android - Mediarecorder 设置参数失败 (setAudioSamplingRate)

arrays - c 函数是否可以同时接受 double 和 long double 参数?

java - 复合分配的自动(取消)装箱失败

c++ - 编译没有ros的roscpp(使用g++)

c++ - 防止在 C++ 中调用基本赋值运算符

oracle - PLSQL - 创建带参数的过程,但只允许 2 个值

带有关键字参数的 JavaScript 字符串

伴随对象中的Scala隐式Numeric [T]