模板元编程在这里 ( static const int value = 1 + StarCounter<\U>::value;
) 如何打印出 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;
}
最佳答案
第一个模板创建了一个结构,当你调用 StarCounter<U>::value
时它总是返回 0 .
第二个模板专门用于第一个模板,用于使用指针的情况。所以当你用 StarCounter<U*>::value
调用它时, 使用第二个模板,而不是第一个,它将返回 StarCounter<U>::value + 1
.请注意,它会在每个递归步骤中删除指针。
所以调用StarCounter<int***>::value
将花费到:
StarCounter<int***>::value // second template is used due to pointer
1 + StarCounter<int**>::value // second template is used due to pointer
1 + 1 + StarCounter<int*>::value // second template is used due to pointer
1 + 1 + 1 + StarCounter<int>::value // no pointer here, so first template is used
1 + 1 + 1 + 0
3
关于c++ - 这个模板元程序中的 int*** 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41206412/