[英]Is it possible to legally overload a string literal and const char*?
[英]String literal vs const char* function overload
我有一個我想用於const char*
的函數,但它僅適用於字符串文字,因為它們被賦予了特殊的規則以允許初始化數組。 第二個重載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.
}
有沒有辦法允許const char*
初始化數組?
我已經試過了:
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));
}
我覺得
const char* s = "hello";
是指向只讀內存中某個字符串文字的指針,並且編譯器無法推斷出數組大小,因此它選擇了第二個重載。
您可以使用
const char s[] = "hello";
不,您不能使用指針初始化數組。 字符串文字語法是const char s[]
的特殊縮寫,您的工作代碼大致相當於
static const char s[]{'h','e','l','l','o','\0'};
foo(s);
因此,您可以將數組(包括字符串文字)傳遞給模板函數,但不能傳遞指針(包括指向字符串文字的指針)。
另一方面,數組可以衰減到指針,這就是為什么數組和指針都可以傳遞給第二個重載的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.