c++ - 这个模板元程序中的 int*** 是如何工作的?

标签 c++ templates template-meta-programming

模板元编程在这里 ( 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/

相关文章:

c++ - 使用 boost::spirit 解析 Newick 语法

c++ - 平方根元函数?

c++ - 是否可以使用 c++11 中的模板元编程创建一个填充大小为 N 的零的 vector

c++ - 如何在具有不同模板参数的 C++ 模板之间隐式转换

c++ - 缠绕式类型转换

c++ - Qt C++ - 访问动态创建的 Widget (QLineEdit)

c++ - 修改 char *const 字符串

c++ - 模板参数类型被编译器视为完整的,但其定义尚不可见

c++ - 是依赖类型依赖的非静态数据成员的非限定名称

c++ - 递归结构列表有什么明显的缺点吗?