Search code examples
c++objectabstract-classevaluationclass-template

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.


Solution

  • 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.