我需要帮助来理解这段代码。没有可用的循环,所以我知道在编译时如何处理模板,如何获取所有参数,为什么它调用相同的变量“ 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
并在body构造函数中将其递增(c
成为1
)TCount<A,B,Z>
继承c
并在body构造函数中将其递增(c
成为2
)TCount<B,A,B,Z>
继承c
并在body构造函数中将其递增(c
成为3
)TCount<A,B,A,B,Z>
继承c
并在body构造函数中将其递增(c
成为4
)本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句