我需要帮助来理解这段代码。没有可用的循环,所以我知道在编译时处理的模板如何获取所有参数,为什么它调用相同的变量“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;
}
最佳答案
诀窍在于类定义的递归。
我的意思是...当你定义
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
)
关于c++ - 为什么可变参数模板在 C++ 中表现得像这样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56202553/