Can someone explain how the following base template and specialization is instantiated to produce the correct result? I'm particularly unclear on how the <U[N]>
template parameter is interpreted. Is it because the non-type template parameter is recursively referring to the last/outer dimension?
I've seen this template-related question which was pointed out to me as being similar but it doesn't deal with template metafunctions, multidimensional arrays, or recursion.
//The primary template handles scalar (non-array) types as a base case
template <class T>
struct rank { static size_t const value = 0U; };
//The partial specialization recognizes an array type:
template <class U, size_t N>
struct rank<U[N]> {
static size_t const value = 1u + rank<U>::value;
};
int main() {
using array_t = int[10][20][30];
//yields 3u (at compile time)
std::cout << "rank is " << rank<array_t>::value << std::endl;
}
This code is from this youtube video on template metaprogramming.
These get instantiated:
struct rank<int> { static size_t const value = 0U; };
struct rank<int[10]> {
static size_t const value = 1u + rank<int>::value;
};
struct rank<int[10][20]> {
static size_t const value = 1u + rank<int[10]>::value;
};
struct rank<int[10][20][30]> {
static size_t const value = 1u + rank<int[10][20]>::value;
};
int main() {
using array_t = int[10][20][30];
//yields 3u (at compile time)
std::cout << "rank is " << rank<array_t>::value << std::endl;
}