为什么可变参数模板在 C++ 中表现得像这样?

Why do variadic templates behave like this in c++?

我需要帮助来理解这段代码。没有可用的循环,所以我知道在编译时处理的模板如何获取所有参数,为什么它调用相同的变量“c”,即使它只在专门的“Z”版本 ?

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

using namespace std;

class Z
{
    Z() {}
    virtual ~Z() {}
};

class A
{
    A() {}
    virtual ~A() {}
};

class B
{
    B() {}
    virtual ~B() {}
};

template <class P, class... args>
class TCount : public TCount<args...>
{
public:
    TCount() : TCount<args...>() { this->c++; }
    virtual ~TCount() {}
};

template <>
class TCount<Z>
{
protected:
    int c;

public:
    TCount() { c = 0; }
    int getC() { return c; }
    virtual ~TCount() {}
};

int main()
{
    TCount<A, B, A, B, Z> tCount;
    cout << tCount.getC() << endl;
    return 0;
}

诀窍在于 class 定义的递归。

我的意思是...当你定义

TCount <A,B,A,B,Z> tCount;

你有那个

  • TCount<A,B,A,B,Z> 继承自 TCount<B,A,B,Z>
  • TCount<B,A,B,Z> 继承自 TCount<A,B,Z>
  • TCount<A,B,Z> 继承自 TCount<B,Z>
  • TCount<B,Z> 继承自 TCount<Z>
  • TCount<Z>定义c并将其初始化为零
  • TCount<B,Z> 继承 c 并在主体构造函数中递增它(c 变为 1
  • TCount<A,B,Z> 继承 c 并在主体构造函数中递增它(c 变为 2
  • TCount<B,A,B,Z> 继承 c 并在主体构造函数中递增它(c 变为 3
  • TCount<A,B,A,B,Z> 继承 c 并在主体构造函数中递增它(c 变为 4