r/cpp_questions • u/onecable5781 • 7d ago
OPEN Operator + overloads on std::string
Consider https://godbolt.org/z/oY9r59P5E
#include <string>
const char *temp = "Hello";
std::string returnstring(){
return "abc";
}
int main(){
std::string abc = temp + returnstring() + "_";
std::string def = temp + "_";
}
The second line in main() does not compile with the error of "invalid operands". The first line compiles fine and that can only be due to the intervening "returnstring()" call which returns an std::string, somehow.
What is the cleanest way to get the intent behind the second line to compile? In my application, I cannot change const char * temp into an std::string.
8
Upvotes
View all comments
2
u/Total-Box-5169 6d ago
The prvalue array "_" decays into pointer, and two pointers can't be added. On top of that you can't provide a custom overload because at least one parameter must have class or enumerated type.
Usually the best way to do it is to use std::string as a string builder. If you want to keep the syntax as close as possible to what you wrote there are standard string literals that allow you to define a std::string prvalue just by adding s as a suffix: