为什么使用"typeid"时必须输入数组的长度?

Why do I have to enter length of array while using "typeid"?

本文关键字:数组 输入 typeid 为什么      更新时间:2023-10-16

我正在学习c++11,虽然我想测试typeid语法,但我不明白为什么我必须输入数组的长度才能识别它

例如:

 char name[9];
 if (typeid(name) == typeid(char []) // without length 
     cout<<"Okay"<<endl;             // not print

 char name[9];
 if (typeid(name) == typeid(char [9]) // with length 
     cout<<"Okay"<<endl;              // okay

但如果我不写length9,它就不起作用,我必须输入ength9。为什么

因此:

if (typeid(name) == typeid(char))       // only char wrong | ok | logical 
if (typeid(name) == typeid(char *))     // by * wrong      | ok | logical
if (typeid(name) == typeid(char []))    // onle [] wrong   | don't understand 
if (typeid(name) == typeid(char [9]))   // okay            | but why ?

我希望typeid(char[])能起作用。实际上数组的长度是多少?

char[2]不是char[3]。它们是完全分离的类型。元素的数目不仅仅是一个参数。它是类型本身的一部分。

您可以考虑元素的数量如下:

template <class T, size_t N>
class array{
public:
    T[N] data;
}

如果你想使用这个类,你应该写:

array<int,6> foo;
array<int,7> bar;

在编译时,数组类型将被转换为如下类型:

array_int_6 foo;
array_int_7 bar;

CCD_ 7。从而导致:typeid(foo) != typeid(bar)typeid(array<int,6>) != typeid(array<int,7>)

数组的大小是其类型的一部分。char[7]char[8]不是一回事。我们可以用证明这一点

void foo(char (&arr)[6]) {}

现在使用该函数,我们只能传递类型为char[6]的数组。看看这个例子,你可以看到编译器会抱怨数组与函数中指定的大小不匹配。