简体   繁体   中英

How to overload operator + for const char* and int

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

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM