c ++模板专业化中T []的类型是什么

Fra*_*ahm 0 c++ type-traits c++11

我对std::remove_extent(visual studio 11)的实现有疑问

    template<class _Ty>
        struct remove_extent
        {
        typedef _Ty type;
        };

    template<class _Ty, unsigned int _Ix>
        struct remove_extent<_Ty[_Ix]>
        {
        typedef _Ty type;
        };

    template<class _Ty>
        struct remove_extent<_Ty[]> //what for?
        {
        typedef _Ty type;
        };
Run Code Online (Sandbox Code Playgroud)

我刚试过这个: std::cout << typeid(int[]).name() << '\n';

输出是:int [0],所以我认为_Ty[]代表_Ty[0].

但是专业的目的是什么_T[0],我认为第二个案件就是为此而处理的.

另外,我真的怀疑if是否T [0]是有效类型,如果是这样,在哪种情况下你会使用它?

Mik*_*our 5

T[]是一个未知大小的数组; 不完整的类型,不同于任何大小的数组类型.看起来你的编译器有效但有些混乱,使用其他无效T[0]的字符串表示形式.

因此需要这种专业化,因为它不会被大小数组的部分特化所覆盖.

如果是这样,在哪种情况下你会使用它?

您不会使用零大小的数组,因为这不是有效类型.

您可以在不同的位置使用不完整的类型(包括未知大小的数组),例如变量声明.例如:

extern int array[];                           // declaration with incomplete type
std::remove_extent<decltype(array)>::type x;  // OK, gives "int"
array[3] = 42;                                // OK, array decays to pointer

template <size_t N> size_t size(int (&a)[N]) {return N;}
std::cout << size(array) << "\n";             // Error, needs complete type

// somewhere else
int array[17];                                // definition with complete type
std::cout << size(array) << "\n";             // OK, size is known
Run Code Online (Sandbox Code Playgroud)