Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/136.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 字符串文字vs常量字符*函数重载_C++_String - Fatal编程技术网

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