考虑以下计划(参见实时演示here.)
#include <iostream>
#include <type_traits>
int main()
{
struct T{ virtual void foo()=0;};
std::cout<<std::boolalpha;
std::cout<<std::is_array<int[3]>::value<<'\n';
std::cout<<std::is_array<T>::value<<'\n';
std::cout<<std::is_array<T1[2]>::value<<'\n';
std::cout<<std::is_array<T[3]>::value<<'\n'; // why uncommenting this line causes compile time error?
}
我知道创建抽象类的对象是不可能的。这里T是抽象的,因此不可能创建struct T的对象。 但请考虑以下声明
std::cout<<std::is_array<T[3]>::value<<'\n';
为什么它会给我一个错误?该语句仅检查给定类型是否为数组。这是否意味着如果T是数组
&安培;静态成员value
的值计算为true
,然后将创建对象数组? 但是,为什么需要在这里创建数组?
什么是创建数组的需要如果我不能使用该数组?这不仅仅是浪费记忆吗?
那么为什么以下语句不会给出任何编译器错误?
std::cout<<std::is_array<T>::value<<'\n';
我在这里理解错了什么?请帮帮我。
答案 0 :(得分:5)
N4567§8.3.4数组[dcl.array] p1(强调我的)
在声明
Add Keyboard Shortcut
中First Stroke
的格式为
T D
<子>D
子>D1 [ constant-expression
<子>opt
子>并且声明
] attribute-specifier-seq
中标识符的类型是“ derived-declarator-type-listopt
”,然后是标识符的类型< / em> of D是一种数组类型; [...] T称为数组元素类型;此类型不应是引用类型,(可能是cv-quali fi ed)类型void,函数类型或抽象类类型。
因此,语言规则只是禁止您创建“abstrct类类型”类型。
答案 1 :(得分:2)
您不能拥有抽象类类型的数组。因此,您会收到编译器错误。
但是,为什么需要在这里创建数组呢?有什么需要 创建一个数组如果我不能使用该数组?不仅仅是这个 浪费记忆?
未创建数组,您将其类型作为模板参数传递。编译器发现这是一个抽象类对象的数组,它会抱怨。