[英]Is it possible to legally overload a string literal and const char*?
在C ++ 11中是否可以重載const char*
和字符串文字( const char[]
)? 這樣做的目的是避免在已知字符串長度時調用strlen
來查找字符串長度。
此代碼段在G ++ 4.8和Clang ++ 3.2上中斷:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
template<typename T, int N>
void length(const T(&data)[N]) {
printf("%u[]\n", N - 1);
}
template<typename T>
void length(const T* data) {
printf("*%u\n", (unsigned)strlen(data));
}
int main() {
length("hello");
const char* p = "hello";
length(p);
return 0;
}
錯誤(C聲):
test2.cpp:16:3: error: call to 'length' is ambiguous
length("hello");
^~~~~~
test2.cpp:6:6: note: candidate function [with T = char, N = 6]
void length(const T(&data)[N]) {
^
test2.cpp:11:6: note: candidate function [with T = char]
void length(const T* data) {
^
1 error generated.
有點黑,這似乎起作用:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
template<typename T, int N>
void length(const T(&data)[N]) {
printf("%u[]\n", N - 1);
}
template<typename T>
void length(T&& data) {
printf("*%u\n", (unsigned)strlen(data));
}
const char *foo() {
return "bar";
}
int main() {
length("hello");
const char* p = "hello";
length(p);
length(foo());
return 0;
}
這是有效的C ++ 11嗎? 刪除數組專用化后,字符串文字似乎在T&&
上過載。 是什么導致這種歧義得到解決,但第一個代碼片段中的歧義沒有得到解決?
在第一種情況下,在重載解析期間,您將擁有一個完美的匹配條件,無需對數組進行指針到指針的轉換(屬於“左值轉換”類別,左值到右值以及函數到指針的轉換)。 僅通過左值變換產生的差異不足以使重載分辨率選擇獲勝者。
在第二種情況下,在重載解析期間,兩個函數具有完全相同的參數類型。 然后作為最后的選擇的部分排序發現第二個模板將接受您傳遞給它的所有參數,而第一個模板僅接受數組。 因此,發現第二種情況下的第一個模板更加專業化並采用。
至於您的其他問題-不,不可能專門針對字符串文字進行重載。 您總是會和它們一起捕獲相同大小的數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.