C++ 字符串文字vs常量字符*函数重载
我有一个我想用于C++ 字符串文字vs常量字符*函数重载,c++,string,C++,String,我有一个我想用于const char*的函数,但它只适用于字符串文本,因为它们被赋予了一个允许初始化数组的特殊规则。第二个重载,foo(const char*)将优先用于字符串文本和const char*s,但我的模板重载不适用于const char*s // Errors for const char*. template<typename T, size_t n> void foo(const T (&s)[n]) { } // Selected both times
const char*
的函数,但它只适用于字符串文本,因为它们被赋予了一个允许初始化数组的特殊规则。第二个重载,foo(const char*)
将优先用于字符串文本和const char*
s,但我的模板重载不适用于const char*
s
// Errors for const char*.
template<typename T, size_t n>
void foo(const T (&s)[n])
{
}
// Selected both times if both overloads are present.
void foo(const char*)
{
}
int main()
{
foo("hello");
const char* s = "hello";
foo(s); // Error if foo(const char*) is absent.
}
我认为
const char* s = "hello";
是指向只读内存中某个位置的字符串文本的指针,编译器无法推断数组大小,因此选择第二个重载
你可以用
const char s[] = "hello";
不,不能用指针初始化数组。字符串文字语法是
const char s[]
的特殊缩写,您的工作代码大致相当于
static const char s[]{'h','e','l','l','o','\0'};
foo(s);
因此,可以将数组(包括字符串文本)传递给模板函数,但不能传递指针(包括指向字符串文本的指针)
另一方面,数组可以衰减为指针,这就是为什么数组和指针都可以传递给第二个重载
static const char s[]{'h','e','l','l','o','\0'};
foo(s);