-1

I need help understanding some code.

I have read in other places that passing a string literal as a const char* is legal. But, in the last line of this code from cppreference for user-defined string literals, it says that there is no literal operator for "two". Why is that, if the string literal "two" can be passed to the function taking const char*?

long double operator "" _w(long double);
std::string operator "" _w(const char16_t*, size_t);
unsigned operator "" _w(const char*);


int main() {
    1.2_w; // calls operator "" _w(1.2L)

    u"one"_w; // calls operator "" _w(u"one", 3)

    12_w; // calls operator "" _w("12")

    "two"_w; // error: no applicable literal operator
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Colin Hicks
  • 348
  • 1
  • 3
  • 13

2 Answers2

3

Because a user-defined literal operator that works on a character string must have two parameters: a pointer to the characters, and a length (see section 3b in your cppreference link). The example operator you think should be called lacks this length parameter.

For it to work, the declaration should be

unsigned operator "" _w(const char*, size_t);
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
0

Can a string literal be passed to a function that takes const char*?

Yes.

An example:

void foo(const char*);
foo("two"); // works

You've linked to and quoted the documentation of user defined string literals. User defined string literals are a separate thing from string literals.

but in the last line of this code from cppeference for user defined string literals, it says that there is no literal operator for "two".

Correction: There is no user defined string literal for _w in the example. "two" is a string literal. "two"_w is a user defined string literal, but since there is no declaration for T operator "" _w(const char*, size_t) in the example, that is an error.

Why is that if the string literal "two" can be passed to the function taking const char*?

Whether "two" can be passed into a function taking const char* is completely separate from whether you have defined a user defined string literal.

eerorika
  • 232,697
  • 12
  • 197
  • 326