Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to tell C++11 to use std::string instead of const char*?

Tags:

c++

c++11

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.

like image 345
Brennan L Avatar asked Nov 18 '25 02:11

Brennan L


2 Answers

In c++14 and later:

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

In c++11:

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");
like image 139
Yakk - Adam Nevraumont Avatar answered Nov 19 '25 16:11

Yakk - Adam Nevraumont


The easiest solution for the case of 2 string literals:

print("Foo " "Bar");

Otherwise:

print(std::string("Foo ") + "Bar");
like image 44
rustyx Avatar answered Nov 19 '25 17:11

rustyx