1

When initializing a std::string like this:

std::string { "hello" + " c++ " + " world" };  // error

It errors because const char* cannot be added.

Meanwhile:

std::string { "hello" " c++ " " world" };  // ok

It works thanks to compiler magic.

And then, according to Google's coding-guide, I use constexpr since statements should be not be hard coded:

constexpr const char* HELLO = "hello";
constexpr const char* LANG_CPP = " c++";
constexpr const char* WORLD = " world";

Now things are different:

std::string str { HELLO LANG_CPP WORLD };  // error

Implicit concatenation doesn't work anymore.

Eventually, I wrote code like this:

std::string str = HELLO;
str += LANG_CPP;
str += WORLD;

Other options like below are not appealing to me:

std::string str = std::string(HELLO) + std::string(LANG_CPP) + std::string(WORLD);
std::string str = HELLO + std::string(LANG_CPP) + WORLD;

Do you have alternatives that are better looking?

Update: I have simplified the code. In order to focus on the matter I am concerned with.

My original code looked like this:

sql = "delete from " TABLE_NAME ";";
sql = "insert into " TABLE_NAME "values(" var1 ", " var2 ");";

By the way, the result of concatenation is not required to be a string, const char* is ok, too.

0

2 Answers 2

3

If you are using C++14 or later you can write

sql = "delete from "s + TABLE_NAME + ";"s;
Sign up to request clarification or add additional context in comments.

4 Comments

first of all thx for your quick advice. if i want to use string literal then implicit concatenation just fit. the thing is to use (constexpr) const char *
You want TABLE_NAME to be a constexpr const char*? The above code works in that case.
"delete from " is also hard coded in this case.. i think it need to be replaced like constexpr const char * DELETE_COMMAND = "delete from ";
Note that you need using namespace std::string_literals; to use the ""s operator.
1

The only way to make this work:

std::string str { HELLO LANG_CPP WORLD };

Is to use preprocessor #define macros instead of constexpr variables, eg:

#define HELLO "hello"
#define LANG_CPP " c++"
#define WORLD " world"

So that the compiler sees this:

std::string { "hello" " c++ " " world" };

You have already covered most other uses of const char*/std::string concatenations, but one you didn't mention is std::ostringstream, eg:

#include <sstream>

constexpr const char* HELLO = "hello";
constexpr const char* LANG_CPP = " c++";
constexpr const char* WORLD = " world";

std::ostringstream oss;
oss << HELLO << LANG_CPP << WORLD;
std::string str = oss.str();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.