Frahm
Frahm

Reputation: 815

c++ what is the type of T[] in template specialization

I have a question about the implementation of 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;
        };

I just tried this: std::cout << typeid(int[]).name() << '\n';

and the output is: int [0], so I presume _Ty[] stands for _Ty[0].

but what is the purpose of specializing for _T[0], I think the second case has handled for that.

Also, I really doubt that if T [0] is a valid type, If so, in which case whould you use that?

Upvotes: 0

Views: 247

Answers (2)

Mike Seymour
Mike Seymour

Reputation: 254691

T[] is an array of unknown size; an incomplete type, different from any sized array type. It seems that your compiler, validly but somewhat confusingly, uses the otherwise invalid T[0] as the string representation of the type.

So this specialisation is needed since it won't be covered by the partial specialisation for sized arrays.

If so, in which case whould you use that?

You wouldn't use an array of zero size, since that's not a valid type.

You can use incomplete types (including arrays of unknown size) in various places, such as variable declarations. For example:

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

Upvotes: 5

Jonathan Wakely
Jonathan Wakely

Reputation: 171403

and the output is: int [0], so I presume _Ty[] stands for _Ty[0].

No, it's not the same, as Mike Seymour's answer says. It looks like a problem with your compiler's type_info name if it says it's the same.

Also, I really doubt that if T [0] is a valid type, If so, in which case whould you use that?

Some compilers allow it as an extension, so this is OK on such compilers:

typedef int empty_array[0];   // typedef for int[0]
int* p = new empty_array;

Upvotes: 1

Related Questions