可以将字符串文字传递给采用 const char* 的函数吗?

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

我需要帮助来理解一些代码。

我在 other places that passing a string literal as a const char* is legal. But, in the last line of this code from cppreference 中读到用户定义的字符串文字,它说 "two" 没有文字运算符。为什么会这样,如果字符串文字 "two" 可以传递给采用 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
}

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

是的。

一个例子:

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

您已链接并引用了用户定义的字符串文字 的文档。 用户定义的字符串文字字符串文字.

是不同的东西

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".

更正:示例中 _w 没有用户定义的字符串文字。 "two" 是一个字符串文字。 "two"_w 是用户定义的字符串文字,但由于示例中没有 T operator "" _w(const char*, size_t) 的声明,所以这是一个错误。

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

是否可以将 "two" 传递给采用 const char* 的函数与您是否定义了用户定义的字符串文字完全分开。

因为作用于字符串的用户定义文字运算符必须有两个参数:指向字符的指针和长度(参见3b部分在您的 cppreference link 中)。您认为应该调用的示例运算符缺少此长度参数。

要让它起作用,声明应该是

unsigned operator "" _w(const char*, size_t);