r/cpp_questions • u/onecable5781 • 3d 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
14
u/Highborn_Hellest 3d ago
Temp is a const char pointer. Def is not. You need to cast temp to string
std:: string (temp)+ "_"; Should work. Such overloads dont exist by default.
7
u/thingerish 3d ago
https://godbolt.org/z/EzEnvazeK
Or use std string literals,
https://godbolt.org/z/oaz8o1d6c
several ways
6
u/UnicycleBloke 3d ago
returnstring() works because the compiler knows it needs to convert the const char* "abc" into a std::string, and there is a std::string constructor it can use for this. The first example works because temp is being added to a std::string, and std::string has a matching overload of operator+(). The second example tries to add two const char* together but there is no operator+() overload for that. You need to explicitly convert one of then to std::string.
4
u/SoerenNissen 3d ago edited 1d ago
but if you don't want to introduce that function, you can do any of
(I prefer the first one)
4
u/alfps 3d ago edited 3d 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.
3
u/Wild_Meeting1428 3d ago
wrap it into a string_view, or even better, use std::format/fmt::format
2
u/Discordbothost 3d ago
The pointer itself can be reassignable. std::string{temp} copies from whatever address temp holds at that point. If temp comes from an API that can return null, check for that before constructing the string. A valid empty C string and a null pointer are different inputs.
2
u/mkhanwrites_ 3d ago
I get the error " error: invalid operands of types ‘const char*’ and ‘const char [2]’ to binary ‘operator+’ ".
It seems the binary operator + is not defined for two C-style string operands. One string needs to be an std::string, because then the use of "+" will invoke the binary operator+ overload for std::string, which is defined for std::string and C-style string operands.
2
u/Total-Box-5169 2d 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:
2
u/DawnOnTheEdge 3d ago edited 2h ago
The language only knows which overload a
operator+member function is supposed to call from the left operand. For this reason, the Standard Library declares bothoperator+(const std::string, const char*)andoperator+(const char*, const std::string)as non-member overloads. It doesn’t change the meaning of adding two built-in pointer types.One way to write what you want is:
std::string def = std::string{temp} + "_";
This will construct a temporary
std::stringand select the overloadoperator+(std::string&&, const char*). This overload appends the right operand to the left operand. It then moves rather than copies the modified source operand to the destination object. A modern compiler that inlines the call might only materialize the prvalues created byoperator+and the constructor when needed. This lets it potentially materialze the result of the concatenation in place at the destination object, and also copy-construct the left operand in place, optimizing away the move.You could also write this out as two lines:
std::string def = temp; def += "_";
This makes explicit that the destination object is being copy-constructed from a C-style string, then appended to in place, with no move, like you would want the compiler to optimize the other versions to.
2
u/Independent_Art_6676 3d ago
unrelated but if you just append a char, use + '_' instead?
decide if you want C strings or C++ strings. strcat could combine all the junk:
But the issue really is that temp is the wrong type, and its making problems for you by forcing you to mix C and C++.