Sha*_*iri 3 c++ arrays typeid c++11
我正在学习c ++ 11,虽然我想测试typeid语法,但我不明白为什么我必须输入数组的长度来识别它?
例如 :
char name[9];
if (typeid(name) == typeid(char []) // without length
cout<<"Okay"<<endl; // not print
Run Code Online (Sandbox Code Playgroud)
char name[9];
if (typeid(name) == typeid(char [9]) // with length
cout<<"Okay"<<endl; // okay
Run Code Online (Sandbox Code Playgroud)
但如果我不写长度 9它不起作用,我必须输入长度9.好吧,为什么?
因此:
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 ?
Run Code Online (Sandbox Code Playgroud)
我希望typeid(char[])能够工作.实际上数组的长度是多少?
char[2]不是别的char[3].它们是完全分离的类型.元素的数量不仅仅是一个参数.它是该类型本身的一部分.
您可以考虑以下元素的数量:
template <class T, size_t N>
class array{
public:
T[N] data;
}
Run Code Online (Sandbox Code Playgroud)
如果你想使用这个类,你应该写:
array<int,6> foo;
array<int,7> bar;
Run Code Online (Sandbox Code Playgroud)
在编译时,数组类型将转换为如下所示:
array_int_6 foo;
array_int_7 bar;
Run Code Online (Sandbox Code Playgroud)
很明显array_int_6 != array_int_7.从而导致:typeid(foo) != typeid(bar)和typeid(array<int,6>) != typeid(array<int,7>)
数组的大小是其类型的一部分.A char[7]和a不是一回事char[8].我们可以证明这一点
void foo(char (&arr)[6]) {}
Run Code Online (Sandbox Code Playgroud)
现在有了这个函数,我们只能传递一个类型的数组char[6].看看这个例子,您可以看到编译器会抱怨与该函数中指定的大小不匹配的数组.
| 归档时间: |
|
| 查看次数: |
478 次 |
| 最近记录: |