Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between T[N] and T[] in template specializations?

Looking at the example implementation of std::is_array, they have the following code:

template<class T>
struct is_array<T[]> : std::true_type {};

template<class T, std::size_t N>
struct is_array<T[N]> : std::true_type {};

When will the T[] specialization be matched and not the T[N] specialization? Why the need for two? I assume this T[] isn't the same as it would be in a function argument where it means the same thing as a pointer right?

like image 719
uk4321 Avatar asked Dec 04 '13 15:12

uk4321


1 Answers

The type T[] is an incomplete type, it is known to be an array but the size (which is also part of the type) is unknown at this point. It can be used in some contexts and in those contexts you may want to check whether the variable that is declared as such is an array or not. While the type of the variable is still incomplete the second specialization of std::array would not match, as the size is unknown.

// test.h
struct Test {
   static int data[];
};
// test.cpp
int Test::data[10];

An TU that only includes the header but has no visibility of test.cpp may want to test whether Test::data is an array or not.

like image 143
David Rodríguez - dribeas Avatar answered Oct 23 '22 11:10

David Rodríguez - dribeas