Search code examples
c++arraystemplatestr1

How does compiler choose between template specializations featuring an array?


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?


Solution

  • 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