1

It's very pointless and troublesome that everytime that you need to concatenate two strings it is necessary to do at least:

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

I would like to overload operator+ and use it in order to always do a concat between tho char* in this way:

std::string mystr = "Ciao " + "Mondo".

How would you do? I'd like to find a best practice. Thank you...

Ah does boost have something to solve this?

jalf
  • 243,077
  • 51
  • 345
  • 550
Andry
  • 16,172
  • 27
  • 138
  • 246
  • 6
    You know, one question mark is sufficient in order to indicate that something is a question. Using six of them in a row does not make it any more of a question. Unless your cat sat on the keyboard, there's no reason for it. – jalf Dec 06 '10 at 12:27
  • STL string concatenation best practices: http://stackoverflow.com/questions/611263/efficient-string-concatenation-in-c – Bojan Komazec Dec 06 '10 at 12:41

3 Answers3

5

You cannot make + work like this. To define an operator overload, at least one of the operands must be a user-defined type.

However, the functionality is built in: if you just put two string literals together "like" "this", they will automatically be joined together at compile time.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • 1
    @Andry: Why would you want to type `"Hello" + "World"` when `"Hello" "World"` (a) is shorter to type and (b) works? – CB Bailey Dec 06 '10 at 12:35
  • @Andry that's just what I finished saying in the first part. Notice, in the second part, that there is no `+` in `"like" "this"`. – Karl Knechtel Dec 06 '10 at 12:50
2

You can't. There is no way to overload operators between built-in types. I'm also not sure why it's so "troublesome". If you do a lot of string operations, then surely one or both parameters will already be of type std::string.

jalf
  • 243,077
  • 51
  • 345
  • 550
1

You can't. Think about it - what is "Ciao " and "Mondo", really? They are static arrays of characters. You can't add static arrays together, as the compiler will helpfully point out for the following code:

#include <iostream>

int main()
{
  std::string mystr = "Ciao " + "Mondo";
  std::cout << mystr << std::endl;
  return 0;
}

(output:

In function 'int main()':
Line 5: error: invalid operands of types 'const char [6]' and 'const char [6]' to binary 'operator+'

That's it. This is pretty much a dupe of: const char* concatenation.

Community
  • 1
  • 1
Asim Ihsan
  • 1,501
  • 8
  • 18