[英]C++ concatenation; string + double; operator+ vs operator+=
gcc v10.2.0, -std=c++11 gcc v10.2.0,-std=c++11
I'm not trying to convert the double value to a literal string using 'std::to_string()'.我不想使用“std::to_string()”将双精度值转换为文字字符串。 Trying to acheive a similar effect of adding an integer to a string but with a double value instead.试图实现将整数添加到字符串但使用双精度值的类似效果。
Expected output: "abcdA"预期输出:“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;
Both the 'operator+' and 'operator+=' methods of 'string' class have a version which accepts a 'char' argument but only the 'operator+=' method seems to receive an implicitly converted value and does not produce an error. 'string' 类的 'operator+' 和 'operator+=' 方法都有一个接受 'char' 参数的版本,但只有 'operator+=' 方法似乎接收隐式转换的值并且不会产生错误。
Why does the compiler choose to pass a converted value to one over the other.为什么编译器选择将转换后的值传递给另一个。
operator +=
is a member function, and not a template by itself. operator +=
是一个成员函数,它本身不是模板。 So for a given string
instance, its RHS argument is char
.所以对于给定的string
实例,它的 RHS 参数是char
。 The compiler will look for a conversion to this type.编译器将寻找到这种类型的转换。
operator +
is a free function template, templated so that it works with any basic_string
instantiation: 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 );
Note that CharT
is used both in the basic_string
argument and as the RHS.请注意, CharT
既用于basic_string
参数又用作 RHS。 This means that the compiler will try to deduce it from both arguments, and needs to arrive at a consistent result.这意味着编译器将尝试从两个参数中推导出它,并且需要得出一致的结果。 But in your addition, the left side is a string
, making CharT
a char
, but the right side is a double
, making CharT
a double
.但是在您的加法中,左侧是一个string
,使CharT
成为char
,但右侧是一个double
,使CharT
成为double
。 This inconsistency is why the compiler cannot select a type for CharT
and thus dismisses the overload completely.这种不一致是编译器无法为CharT
选择CharT
并因此完全CharT
重载的原因。 Then, when it is done looking through all the many overloads of operator +
, it gives up and says that there is no matching function.然后,当它完成查看operator +
所有重载时,它放弃并说没有匹配的函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.