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

Abh*_*ith 10 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;
}
Run Code Online (Sandbox Code Playgroud)

Gru*_*bel 17

第一个模板创建一个结构,在调用时始终返回0 StarCounter<U>::value.

对于使用指针的情况,第二个模板专门针对第一个模板.因此,当您调用它时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
Run Code Online (Sandbox Code Playgroud)

  • @wchargin:好吧,考虑到你不能先读取"那个字段"而不先计算它(实例化模板),看看"调用"词汇来自哪里应该不会太难(一般来说,你想到的是TMP术语)模板实例化为调用,模板字段为所述调用的结果) (4认同)

ale*_*in0 10

StarCounter<int>::value
Run Code Online (Sandbox Code Playgroud)

等于0,因为它与模板的第一个实例化相匹配,其中value明确定义了.

StarCounter<int*>::value = 1 + StarCounter<int>::value
Run Code Online (Sandbox Code Playgroud)

等于1,因为StarCounter<int*>匹配StarCounter<U*>.是的,StarCounter<T>也可以被视为匹配,但StarCounter<U*>更具体,这就是为什么这个首选.

同样的,

StarCounter<int**>::value = 1 + StarCounter<int*>::value
Run Code Online (Sandbox Code Playgroud)

等于2

StarCounter<int***>::value = 1 + StarCounter<int**>::value
Run Code Online (Sandbox Code Playgroud)

等于3.


Mic*_*iak 0

有一个模板StarCounter,其更一般的形式具有value等于 的常数0。因此,当您对大多数类型使用此模板并询问时,value您将得到 0。

该模板还有一个接受指针的专用版本。它的实现也有value等于 1 的常量(因为我们有一个指针,这意味着我们至少有一颗星)加上value该指针指向的类型的值。

如果是三颗星,我们有:

StarCounter<int***>::value = 1 + StarCounter<int**>::value (1) + StarCounter<int*>::value (1) + StarCounter<int>::value (0)