[英]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. 我在其他地方读过,将字符串文字作为const char*
传递是合法的。 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"
. 但是,在这段代码的最后一行中, 来自cppreference的用户定义的字符串文字表示没有"two"
文字运算符。 Why is that, if the string literal "two"
can be passed to the function taking const char*
? 为什么这样,如果可以将字符串文字"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
}
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). 因为处理字符串的用户定义的文字运算符必须具有两个参数:指向字符的指针和长度(请参见cppreference链接中的3b
节)。 The example operator you think should be called lacks this length parameter. 您认为应调用的示例运算符缺少此length参数。
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*? 是否可以将字符串文字传递给采用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". 但是在cppeference的这段代码的最后一行中,对于用户定义的字符串文字,它说没有用于“ two”的文字运算符。
Correction: There is no user defined string literal for _w
in the example. 更正:在示例中, _w
没有用户定义的字符串文字。 "two"
is a string literal. "two"
是字符串文字。 "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. "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 *的函数?
Whether "two"
can be passed into a function taking const char*
is completely separate from whether you have defined a user defined string literal. 是否可以将"two"
传递给采用const char*
的函数,这与您是否已定义用户定义的字符串文字完全不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.