I know this is silly and ugly, but I'm migrating some code automatically. My source language allows implicit conversion between strings and ints, and for example this is allowed:
var = "hello " + 2 print(var) # prints "hello 2"
How can I in C++ overload the + operator for
const char* and
int? I'm getting the error:
error: ‘std::string operator+(char* const&, int)’ must have an argument of class or enumerated type</blockquote> Answer1:
<h3>What you are asking for is illegal</h3>
To legally overload an operator at least one of the operands involved has to be a <em>user-defined type</em>. Since neither
int is <em>user-defined</em>, what you are trying to accomplish isn't possible.
This, what you are trying to do, is intentionally, and explicitly, disallowed in the standard. Don't you think it would be weird if suddenly
1+3 = 42 because someone "clever" have defined an overload for
188.8.131.52p1-2 <strong>Operators in expressions</strong>
If no operand of an operator in an expression has a type that is a class or an enumeration, the operator is assumed to be a built-in operator and interpreted according to Clause 5.
If either operand has a type that is a class or an enumeration, a user-defined operator function might be declared that implements this operator or a user-defined conversion can be neccessary to convert the operand to a type that is appropriate for a built-in operator.</blockquote> </blockquote>
( <strong>Note</strong>: The wording is the same in both <em>C++03</em>, and the next revision of the standard; <em>C++14</em> )