0
votes

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

1
You can't overload operators for built-in types.juanchopanza
There's already a built-in + operator for pointer+integer and integer+pointer. "hello" + 2 yields a pointer to the first 'l' character in the string. Since array indexing is defined in terms of pointer arithmetic, allowing you to hide the predefined operators would be really bad.Keith Thompson
Nothing particularly wrong with "hello " + std::to_string(2).chris
Are you migrating from VB6 to C++ and trying to keep that code? Not a good idea.user2672165
@vz0 do not, do not, I repeat do not overload operator+(std::string, int). Only overload operators on types you own, and you don't own types in std. If you must have a string type that supports + int, create your own that has a std::string field.Yakk - Adam Nevraumont

1 Answers

11
votes

What you are asking for is illegal

To legally overload an operator at least one of the operands involved has to be a user-defined type. Since neither char* nor int is user-defined, 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 operator+(int, int)?


What does the Standard say? (n3337)

13.3.1.2p1-2 Operators in expressions [over.match.oper]

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.

( Note: The wording is the same in both C++03, and the next revision of the standard; C++14 )