Search code examples
c++type-conversionimplicit-conversionuser-defined-literals

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
}

Solution

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