简体   繁体   中英

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

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
}

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM