【问题标题】:Why do variadic templates behave like this in c++?为什么可变参数模板在 C++ 中的行为是这样的?
【发布时间】: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


【解决方案1】:

诀窍在于类定义的递归。

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

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

你有这个

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

【讨论】:

  • 我想说不是TCount 定义了c,而是TCount&lt;Z&gt;。如果我们在此可变参数模板末尾使用其他类,则此代码将不起作用,即TCount&lt; Z, A&gt;
  • 我没有明白你的意思@DmitryKuzminov,为什么它不起作用?
  • @MinaAshraf - 尝试定义,例如,TCount&lt;A, B, A, B&gt;;您会收到编译错误,因为 TCount&lt;A, B&gt; 继承自 TCount&lt;B&gt;TCount&lt;B&gt;TCount&lt;Z&gt; 特化不匹配,因此匹配一般情况,因此从 TCount&lt;&gt; 继承(空可变参数列表)但 TCount 已定义带有一个或多个模板参数;编译错误!
  • 您需要以某种方式停止递归。到目前为止,您已经定义了将一个或多个类作为模板参数的模板类,但是您还没有完全不带参数的类的定义。您还有一个参数 Z 的模板类的特化,它允许您停止 TCount 实例化的情况下的递归
猜你喜欢
  • 2015-07-29
  • 1970-01-01
  • 2021-11-08
  • 1970-01-01
  • 2019-06-15
  • 1970-01-01
  • 2014-05-28
  • 2022-06-13
  • 2020-08-22
相关资源
最近更新 更多