简体   繁体   English

字符串文字vs const char *函数重载

[英]String literal vs const char* function overload

I have a function that I want to work for const char* 's but it only works for string literals because they are given a special rule to be allowed to initialize arrays. 我有一个我想用于const char*的函数,但它仅适用于字符串文字,因为它们被赋予了特殊的规则以允许初始化数组。 The second overload, foo(const char*) will be preferred for both string literals and const char* s, but my template overload will not work for const char* s. 第二个重载foo(const char*)对于字符串文字和const char*都是首选,但是我的模板重载不适用于const char*

// 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.
}

Is there a way to allow const char* s to initialize arrays? 有没有办法允许const char*初始化数组?


I've tried this: 我已经试过了:

template<typename T, size_t n>
void _foo(const T (&s)[n])
{
    std::cout << __PRETTY_FUNCTION__;
}

#define _expand(s) #s
#define expand(s) _expand(s)

void foo(const char* s)
{
    _foo(expand(s));
}

I think that 我觉得

const char* s = "hello";

is a pointer to the string literal somewhere in read only memory, and compiler cannot deduce the array size, so it chooses second overload. 是指向只读内存中某个字符串文字的指针,并且编译器无法推断出数组大小,因此它选择了第二个重载。

You can use 您可以使用

 const char s[] = "hello";

No, you can't initialize an array with a pointer. 不,您不能使用指针初始化数组。 The string literal syntax is a special shorthand for a const char s[] and your working code roughly equivalent to 字符串文字语法是const char s[]的特殊缩写,您的工作代码大致相当于

static const char s[]{'h','e','l','l','o','\0'};
foo(s);

So, you can pass arrays to your template function, including string literals, but you cannot pass pointers, including pointers to string literals. 因此,您可以将数组(包括字符串文字)传递给模板函数,但不能传递指针(包括指向字符串文字的指针)。

On the other hand, arrays can decay to pointers, which is why both arrays and pointers can be passed to your second overload. 另一方面,数组可以衰减到指针,这就是为什么数组和指针都可以传递给第二个重载的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM