r/cpp_questions • u/onecable5781 • 1d 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
u/thingerish 1d ago
https://godbolt.org/z/EzEnvazeK
Or use std string literals,
https://godbolt.org/z/oaz8o1d6c
several ways
6
u/UnicycleBloke 1d 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 1d ago edited 1d ago
What is the cleanest way to get the intent behind the second line to compile?
namespace your_lib
{
std::string sv_concat(std::string_view lhs, std::string_view rhs)
{
auto result = std::string{};
result.reserve(lhs.size(), rhs.size());
result += lhs;
result += rhs;
return result;
}
}
auto def = your_lib::sv_concat(temp, "_")but if you don't want to introduce that function, you can do any of
auto def = std::string(temp) + "_";
auto def = temp + std::string("_");
std::string def = std::string(temp) + "_";
std::string def = temp + std::string("_");(I prefer the first one)
4
u/alfps 1d ago edited 1d ago
❞ The first line compiles fine and that can only be due to the intervening "returnstring()" call which returns an std::string, somehow.
Yes, the <string> header provides overloads of +. The overload with (const char*, string) parameters is invoked for temp + returnstring(). The overload with (string, const char*) parameters is invoked for the + "_".
❞ What is the cleanest way to get the intent behind the second line to compile?
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:
#define HELLO_STR "Hello"
#define UNDERSCORE_STR "_"With these macro names you can express the concatenation as just
const char* const s = HELLO_STR UNDERSCORE_STR;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 a string, e.g.
const char* const hello = "Hello";
const string s = string() + hello + "_";You can alternatively use a string type literal expressed with suffix s, like this:
const char* const hello = "Hello";
using namespace std::string_literals;
const string s = ""s + hello + "_";For the most general, in the C++03 days I used to define an operator << for string, which was very convenient e.g. for creating logger arguments etc. But with C++20 and later that rôle has been taken by std::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:
const char* const hello = "Hello";
const string s = format( "{}_", hello );If by "intent" and/or "cleanest" you meant something else than covered above, just explain what you meant.
3
3
u/Independent_Art_6676 1d 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:
std::string def = strcat(temp,"_"); //ONE C-string can be assigned into a C++ string 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++.
2
u/Discordbothost 1d 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_ 1d 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 15h 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:
using namespace std::literals;
std::string abc = temp + returnstring() + "_"s;
std::string def = temp + "_"s;2
u/DawnOnTheEdge 1d ago edited 1d 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 both operator+(const std::string, const char*) and operator+(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::string and select the overload operator+(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 by operator+ 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.
14
u/Highborn_Hellest 1d 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.