nishantsingh
nishantsingh

Reputation: 4662

Two double quotes around preprocessor token in macro definition

I don't understand the significance of using two double quotes with strings in C++. I saw the following code somewhere:

class str_literal;
static str_literal operator"" _s(const char *s, size_t len);

class str_literal {
private:
  explicit str_literal(const char *s)
      : m_str(s) //&(STRING_LITERAL(s)))
  {}
  const char *m_str;

public:
  friend str_literal operator"" _s(const char *s, size_t len);
};
static str_literal operator"" _s(const char *s, size_t len) {
  return str_literal(s);
}
#define S(str) "" str "" _s

Why not make the constructor public and just do this?

#define S(str) str_literal(str)

Upvotes: 3

Views: 1508

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 546053

They’re unnecessary. Whoever wrote the code probably intended to use the fact that you the preprocessor concatenates successive C string literals into one literal so that e.g. S("hi") results in "" "hi" ""_s, which, in turn, results in "hi"_s.

However, there is no need to have the first "" in the macro definition. And there’s no need for the second "" either, since we can use the token pasting operator ## instead:

#define S(str) str ## _s

This has the exact same effect, and is idiomatic.

Upvotes: 1

Related Questions