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.
7
Upvotes
View all comments
4
u/alfps 7d ago edited 7d ago
Yes, the
<string>header provides overloads of+. The overload with (const char*,string) parameters is invoked fortemp + returnstring(). The overload with (string,const char*) parameters is invoked for the+ "_".Oh that depends on what you mean by "cleanest" and the "intent" is!
Let's say the intent is to concatenate one string literal with another.
The minimal overhead way is to use the language's built in concatenation of literals just by writing them one after the other, and if you want the literals named then the only simple mechanism that works for this is to use macros:
With these macro names you can express the concatenation as just
The rules were tightened in C++11 I think it was, so that now (I believe) you can only do this with literals of the same basic character type, like above.
The most convenient way is instead to use a run time concatenation that produces a
string. This has some overhead but is clean. You can do this by starting with astring, e.g.You can alternatively use a
stringtype literal expressed with suffixs, like this:For the most general, in the C++03 days I used to define an operator
<<forstring, which was very convenient e.g. for creating logger arguments etc. But with C++20 and later that rôle has been taken bystd::format. If the trailing underscore is just something you need one place, so it doesn't have to be named, it can go like this:If by "intent" and/or "cleanest" you meant something else than covered above, just explain what you meant.