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.

8 Upvotes

19 comments sorted by

View all comments

4

u/SoerenNissen 7d ago edited 5d 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)

1

u/encyclopedist 5d ago

Did you mean result.reserve(lhs.size() + rhs.size());?

1

u/SoerenNissen 5d ago

lmao yes