简体   繁体   English

关于is_array模板类评估的困惑

[英]confusion about evaluation of is_array template class

Consider following program (See live demo 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?
}

I know that it isn't possible to create the object of abstract class. 我知道不可能创建抽象类的对象。 Here T is abstract, so it isn't possible to create the object of struct T. But consider the following statement 这里T是抽象的,因此不可能创建struct T的对象。但是请考虑以下语句

std::cout<<std::is_array<T[3]>::value<<'\n';

Why it gives me an error? 为什么给我一个错误? The statement only checks whether a given type is array or not. 该语句仅检查给定类型是否为数组。 Does that mean that If T is array & value of the static member value evaluates to true then array of objects will be created? 这是否意味着如果T是数组,并且静态成员value计算为true ,则将创建对象数组? But, why array is required to be created here? 但是,为什么需要在此处创建数组? what is the need to create an array If I am not able to use that array? 如果我不能使用该数组,需要创建一个数组吗? Isn't this just wastage of memory? 这不只是浪费内存吗?

Then why following statement doesn't give any compiler error? 那么,为什么以下语句没有给出任何编译器错误?

std::cout<<std::is_array<T>::value<<'\n';

What I am understanding wrong here? 我在这里理解错了吗? Please help me. 请帮我。

N4567 § 8.3.4 Arrays [dcl.array]p1 (emphasis mine) N4567§8.3.4数组[dcl.array] p1(强调我的)

In a declaration TD where D has the form 在声明TDD具有以下形式

D1 [ constant-expression opt ] attribute-specifier-seq opt D1 [ constant-expression opt ] attribute-specifier-seq opt

and the type of the identifier in the declaration T D1 is “ derived-declarator-type-list T ”, then the type of the identifier of D is an array type; 并且声明T D1中的标识符的类型为“ derived-declarator-type-list T ”,则D的标识符的类型为数组类型; [...] T is called the array element type ; [...] T称为数组元素类型 this type shall not be a reference type, the (possibly cv-qualified) type void, a function type or an abstract class type . 这个类型不能是引用类型,(可能是cv限定的)void类型,函数类型或抽象类类型

So, the language rule just forbids you from creating the type "array of abstrct class type". 因此,语言规则仅禁止您创建类型“抽象类类型的数组”。

You can't have an array of abstract class type. 您不能具有抽象类类型的数组。 Thus, you get a compiler error. 因此,您会遇到编译器错误。

But, why array is required to be created here? 但是,为什么需要在此处创建数组? what is the need to create an array If I am not able to use that array? 如果我不能使用该数组,需要创建一个数组吗? Isn't this just wastage of memory? 这不只是浪费内存吗?

The array is not created, you pass its type as a template argument. 未创建数组,您将其类型作为模板参数传递。 The compiler sees that this is an array of abstract class objects and it complains. 编译器看到这是一个抽象类对象的数组,并且抱怨。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM