views:

70

answers:

1

I just came across std::tr1::extent template and it puzzled me. I never ever dealt with array type parameters in my life so I don't understand how they work. So, given the code from gcc type_traits

template<typename _Tp, unsigned _Uint, std::size_t _Size>
     struct extent<_Tp[_Size], _Uint>

template<typename _Tp, unsigned _Uint>
     struct extent<_Tp[], _Uint>

how does compiler chooses between those specializations? What type I should pass to extent to get it choose the second one?

+6  A: 
extent<int[], 0>::value == 0 // second one chosen

int[] is an incomplete type, the compiler doesn't know its sizeof value. The outermost dimension may stay incomplete, because it's not important for the array to function correctly in most contexts (in particular, indexing will still work). Something like int[1][] wouldn't be a correct type anymore.

extent<int[2], 0>::value == 2 // first one chosen

Sure this can be nested:

extent<int[][2], 0>::value == 0 // second one chosen, with `_Tp` being `int[2]`
extent<int[][2], 1>::value == 2 // second one chosen again
Johannes Schaub - litb
So the second one will be chosen any time there's empty square brackets ([]) in the declaration?
vava
Yes, indeed. That's because `T[]` doesn't match `T[N]`.
Johannes Schaub - litb
Hm, looks like despite the logic, when `extent<_Tp[_Size], _UInt>` matches against `extent<int[1][2]>`, `_Tp` gets `int[2]` not `int[1]`. But `(int [1])[2]` seems to be so more intuitive...
vava
You have to consider it as an "array of _Size _Tp", not as a pure textual replacement. The actual rule is more complicated. The rule is that in `T d;` if `d` is `d1[N]`, and the type of `T d1;` is `X T`, then `d` has type `X array of N T`. Apply it for `int i[1];`: `d` is `d1[1]`, and type of `int i;` is "int" (X is empty, `T` is int), `d` has type `array of 1 int`. And applying for `int i[1][2];`: `d` is `d1[2]`. Type of `int i[1];` was `array of 1 int` so `X` is `array of 1`. Overall type is `X array of 2 int` = `array of 1 array of 2 int`.
Johannes Schaub - litb