在标准中是否明确规定const数组元素的类型与非const数组元素的类型不同?以下是我的代码以及VC2010和GCC4.8.0的输出。
谢谢。
#include <iostream>
#include <typeinfo>
#include <ios>
int main(){
int arr_a[] = {1, 2};
int const arr_b[] = {3, 4}; // or const int arr_b[] = {3, 4};
std::cout << typeid(arr_a).name() << "\n";
std::cout << typeid(arr_b).name() << "\n";
std::cout << "Same type: " << std::boolalpha << (typeid(arr_a) == typeid(arr_b)) << ".\n";
}
int [2]
int const [2]
Same type: false.
A2_i
A2_i
Same type: true.
typeid
似乎忽略了顶层的const
,但不要轻信它。 - gx_const
。问题是,如果const int a[2]
有一个**顶层const
**。 - MWidconst int a[2]
是一个_cv-qualified_类型(参见8.3.4和3.9.3)。因此,gcc的输出是正确的。但是arr_a
和arr_b
的类型是不同的。如果您想根据cv限定符区分类型,则不能使用typeid
。 - MWidtypeid
知道两种类型是否相同,特别是涉及到const
的时候(感谢您提供了有关标准的参考)。 - gx_const int a[2]
的类型是 _array of 2 const int_,但a
的类型是_cv-qualified_。忽略这个顶层的 const 意味着将a
的类型替换为 _array of 2 int_。 - MWid