简体   繁体   中英

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

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? 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)

In a declaration TD where D has the form

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 is called the array element type ; this type shall not be a reference type, the (possibly cv-qualified) type void, a function type or an abstract class type .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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