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

Show parent comment

3

u/onecable5781 7d ago

If you introduce an std::string somewhere in the first two operands, it riples through the entire chain of + operators to eventually produce one combined std::string object.

I imagined so. In a more general case, with n (>2) operands, I suppose still the same holds: one of the first two of n operands has to be an std::string assuming the compiler evaluates L to R ? It would not work if only the last of, say, 10 operands is an std::string while all of the others are const char * ?

3

u/TeraFlint 7d ago

You are correct. The associativity of + is left-to-right.

This means, that the type information also flows from left to right.

2

u/flyingron 7d ago

x + y + z means (x + y) + z as far as the syntax goes as + is left-to-right associative.

Note that just refers to the interpretation, not the order of evaluation.