Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up
std::string tmp;
tmp +=0;//compile error:ambiguous overload for 'operator+=' (operand types are 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' and 'int')
tmp +=1;//ok
tmp += '\0';//ok...expected
tmp +=INT_MAX;//ok
tmp +=int(INT_MAX);//still ok...what?

The first one argues that passing integer as argument, right? Why others passes compilation?I tested on Visual C++ and g++, and I got the same result above. So I believe I miss something defined by standard. What is it?

share|improve this question
3  
int will be converted to char. but for 0 its difficult to say whether its NULL or int 0 – Praveen 10 hours ago
up vote 23 down vote accepted

The problem is that a literal 0 is a null pointer constant. The compiler doesn't know if you meant:

std::string::operator +=(const char*);  // tmp += "abc";

or

std::string::operator +=(char);         // tmp += 'a';

(better compilers list the options).

The workround (as you have discovered) is to write the append as:

tmp += '\0';

(I assume you didn't want the string version - tmp += nullptr; would be UB at runtime.)

share|improve this answer
    
Should the compiler really consider +=(char)? – Bathsheba 10 hours ago
4  
Yes. char is a integral type, and an integer is implicitly convertable to char. +=(char) is the overload that is being invoked in all the non-ambiguous cases. – Martin Bonner 10 hours ago

The 0 literal is implicitly convertible to all pointer types (resulting in their respective null pointer constants). Therefore it results in two equally valid conversion sequences for matching std::strings appending operator.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.