甚至有可能使用与简单指针不同的函数来调用在编译时已知大小的数组?我尝试了所有知道的技巧。
template <typename T>
int length(const T* t) {
return -1;
}
template<typename T, int N>
int length(const T (&)[N]) {
return N;
}
int main() {
return length("abc");
}
Run Code Online (Sandbox Code Playgroud)
gcc给出以下错误:
source>: In function 'int main()':
<source>:13:24: error: call of overloaded 'length(const char [4])' is ambiguous
return length("abc");
^
<source>:13:24: note: candidates are:
<source>:2:5: note: int length(const T*) [with T = char]
int length(const T* t) {
^
<source>:7:5: note: int length(const T (&)[N]) [with T = char; int N = 4]
int length(const T (&)[N]) {
^
Run Code Online (Sandbox Code Playgroud)