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

标签 c++ class templates recursion variadic-templates

我需要帮助来理解这段代码。没有可用的循环,所以我知道在编译时处理的模板如何获取所有参数,为什么它调用相同的变量“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/

相关文章:

c++ - 如何使用类型特征正确推导出引用参数

c++ - Glvalue 引用一个基类子对象

c++ boost 分割字符串

c++ - Windows 手机 C++

可以保存整数或字符串的 C# 类属性

java - 继承类将所有继承的公共(public)方法更改为私有(private)方法

php - 从变量名创建对象

c# 使用泛型函数将参数传递给具有许多重载的函数

c++ - 如何从类内部实例化的对象访问私有(private)变量

c++ - 如何初始化指针成员以指向其封装实例?