c++ - 为什么 const char[] 的类型推导与 const char * 不同?

标签 c++ arrays templates constants

在第一次通话中,当我通过 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 = {};

这意味着当 Tchar[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/

相关文章:

java - 如何将对象节点的Json数组解析为不同的dto对象

javascript - 使用携带另一个数组的对象异步循环数组

php - 使用特殊字符对数组进行排序

C++,模板化模板规范

c++ - 未解析的外部符号 - 构造函数

c++ - Stringify 和 Unstringify 模板参数

c++ - 适用于(C 或 C++)Windows 的文本基础用户界面库?

c++ - 提取可变参数模板参数包并将其用于类型特征元函数中的另一个可变参数模板?

c++ - 在提供 JSON 数据的 C++/Qt(充当服务器)中创建简单的 WebService

c++ - 分离接口(interface)和实现的问题