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.

2
  • Does this answer your question? How to concatenate two strings in C++? Commented May 6, 2021 at 4: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. Commented May 8, 2021 at 7:44

2 Answers 2

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"); 
Sign up to request clarification or add additional context in comments.

1 Comment

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.
5

The easiest solution for the case of 2 string literals:

print("Foo " "Bar"); 

Otherwise:

print(std::string("Foo ") + "Bar"); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.