Search code examples
c++stringoperator-overloadingstring-literalsuser-defined-literals

Is this string addition a valid expression?


I was curious if the compound assignment operators are valid for multiple parameters. My guess is += will have no side-effect but may not be the same case with "-=".

std::string a; 
a += "Hello" + " "+"World"; // doesn't compile
std::string name = "Old";
a += "Hello" + name +"World"; // compiles

Solution

  • This is not a valid expression because there is no operator + for string literals

    "Hello" + " "+"World
    

    (more precisely for pointers because in expressions string literals with rare exceptions are converted to pointers to their first symbols.)

    Instead you could write

    std::string a; 
    ( ( a += "Hello" ) += " " ) += "World";
    

    But it would be more readable if to write

    a += "Hello";
    a += " ";
    a += "World";
    

    Or as @Bathsheba pointed out in a (valuable) comment to my answer you could use a user-defined string literal the following way

    #include <string>
    #include <iostream>
    
    int main()
    {
        using namespace std::string_literals;
        std::string a; 
        a += "Hello"s + " " + "World";
    
        std::cout << a << '\n';
    }
    

    As for this statement

    a += "Hello" + name +"World";
    

    then it can be rewriten using the operators defined for the class std::basic_string

    template<class charT, class traits, class Allocator>
    basic_string<charT, traits, Allocator>
    operator+(const charT* lhs, const basic_string<charT, traits, Allocator>& rhs);
    

    and

    template<class charT, class traits, class Allocator>
    basic_string<charT, traits, Allocator>
    operator+(basic_string<charT, traits, Allocator>&& lhs, const charT* rhs);
    

    like

    a += operator +( operator +( "Hello", name ), "World" ); 
    

    For example

    #include <string>
    #include <iostream>
    
    int main()
    {
        std::string a;
        std::string name = "Old";
    
        a += operator +( operator +( "Hello ", name ), " World" ); 
    
        std::cout << a << '\n';
    }
    

    Take into account that each operator returns an object of the type std::basic_string for which the operator + is defined. That is in each call of the operators there is present an object of the type std::basic_string as an argument.