r/cpp_questions • • 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

19 comments sorted by

View all comments

4

u/alfps 7d ago edited 7d 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.