gcc v10.2.0,-std=c++11
我不想使用“std::to_string()”将双精度值转换为文字字符串。试图实现将整数添加到字符串但使用双精度值的类似效果。
预期输出:“abcdA”
string s { "abcd" };
double d { 65.1 };
// s = s + d; // Error. no match for ‘operator+’ (operand types are ‘std::string’ {aka ‘std::__cxx11::basic_string<char>’} and ‘double’)
s += d;
Run Code Online (Sandbox Code Playgroud)
'string' 类的 'operator+' 和 'operator+=' 方法都有一个接受 'char' 参数的版本,但只有 'operator+=' 方法似乎接收隐式转换的值并且不会产生错误。
为什么编译器选择将转换后的值传递给另一个。
operator +=是一个成员函数,而不是它本身的模板。所以对于给定的string实例,它的 RHS 参数是char。编译器将寻找到这种类型的转换。
operator +是一个免费的函数模板,模板化以便它可以与任何basic_string实例化一起使用:
template<class CharT, class Traits, class Alloc>
std::basic_string<CharT,Traits,Alloc>
operator+( const std::basic_string<CharT,Traits,Alloc>& lhs,
CharT rhs );
Run Code Online (Sandbox Code Playgroud)
请注意,CharT它既用于basic_string参数又用作 RHS。这意味着编译器将尝试从两个参数中推导出它,并且需要得出一致的结果。但是在您的加法中,左侧是 a string,使CharTa char,而右侧是 a double,使CharTa double。这种不一致是编译器无法为其选择类型CharT并因此完全消除重载的原因。然后,当它完成查看 的所有重载时operator +,它放弃并说没有匹配的函数。