2

Im trying to migrate code from another language that allows concatonation of strings with the '+' operator.

//defintion 
void print(std::string s) {
    std::cout << s;
}
//call
print("Foo " + "Bar");

The issue I'm having is that c++ sees "Foo " and "Bar" as const char* and cannot add them, is there any way to fix this. I have tried including the string library to see if it would change them automatically but that didnt seem to work.

Casey
  • 10,297
  • 11
  • 59
  • 88
Brennan L
  • 23
  • 4
  • Does this answer your question? [How to concatenate two strings in C++?](https://stackoverflow.com/questions/15319859/how-to-concatenate-two-strings-in-c) – Michael Hall May 06 '21 at 04:42
  • not an answer, but do pass strings between functions as `const std::string& s` instead of as `std::string s`. Avoids a copy and enables opitimizations. – selbie May 08 '21 at 07:44

2 Answers2

5

In and later:

using namespace std::literals;
print("Foo "s + "Bar");

In :

std::string operator "" _s(const char* str, std::size_t len) {
    return std::string(str, len);
}

print("Foo "_s + "Bar");

Or, in all versions:

print(std::string("Foo ") + "Bar");
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
  • 1
    This is a good solution in general, but as the OP said in comment: "*I forgot to mention that I was in c++11*", so this won't work for the OP specifically. – Remy Lebeau May 05 '21 at 22:45
5

The easiest solution for the case of 2 string literals:

print("Foo " "Bar");

Otherwise:

print(std::string("Foo ") + "Bar");
rustyx
  • 80,671
  • 25
  • 200
  • 267