在第一次通话中,当我通过 char const []
转换成参数为 T const a
的模板函数, T
推导出为 char const *
这是合理的,因为 const
指的是衰减指针。
但是,当参数类型更改为 T const & a
时, T
推导出为 char[7]
.从上面的观点来看,为什么const
没有限定整个数组类型?
template <typename T>
void show1(T const a) {
// input is const char *
// T is char const *
// a is char const * const
}
template <typename T>
void show2(T const & a) {
// input is char const [7]
// T is char[7]
// a is char const (&)[7]
}
int main() {
const char s[] = "asdasd";
show1(s);
show2(s);
}
最佳答案
why doesn't the
const
qualify the whole array type
因为对于 array type ,
(强调我的)
Applying cv-qualifiers to an array type (through typedef or template type manipulation) applies the qualifiers to the element type, but any array type whose elements are of cv-qualified type is considered to have the same cv-qualification.
// a and b have the same const-qualified type "array of 5 const char" typedef const char CC; CC a[5] = {}; typedef char CA[5]; const CA b = {};
这意味着当
T
是 char[7]
T const
导致类型 char const[7]
,然后 T const&
(即 a
的类型)是 char const (&)[7]
.另一方面,当您传递数组
s
时带类型 const char[7]
,数组也被认为是 const 限定的。所以给定参数类型 T const&
, T
推导出为 char[7]
(但不是 char const[7]
)。
关于c++ - 为什么 const char[] 的类型推导与 const char * 不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63371807/