How is template metaprogramming working here (static const int value = 1 + StarCounter<\U>::value;) to print out 3 ?
#include <iostream>
template <typename T>
struct StarCounter
{
static const int value = 0;
};
template <typename U>
struct StarCounter<U*>
{
static const int value = 1 + StarCounter<U>::value;
};
int main()
{
std::cout << StarCounter<int***>::value << std::endl;//How is it printing 3?
return 0;
}
There is a template
StarCounterwhich in it's more general form has constantvalueequal to0. So when you use this template for most of the types and ask for thevalueyou will get 0.This template has also a specialized version which accepts pointers. It's implementation also has constant
valuewhich is equal to 1 (as we have a pointer which means we have at least one star) plus value ofvalueof type which this pointer points to.In case of three stars we have:
StarCounter<int***>::value = 1 + StarCounter<int**>::value (1) + StarCounter<int*>::value (1) + StarCounter<int>::value (0)