【发布时间】:2019-10-05 17:43:48
【问题描述】:
我需要帮助来理解这段代码。没有可用的循环,所以我知道在编译时处理的模板如何获取所有参数,以及为什么它调用相同的变量“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;
}
【问题讨论】:
-
正如你所说的“模板,我知道是在编译时处理的”模板它自己在编译时处理而不是数据成员!
标签: c++ class templates recursion variadic-templates