跟踪专用模板对象的枚举成员值

时间:2016-07-22 14:48:35

标签: c++ enums template-specialization

我有一个结构模板,其递归定义的枚举值如下:

template <unsigned x, unsigned y>
struct Special
{
  enum { value = x * Special<x-1, y-1> :: value; }
};

template <unsigned n>
struct Special<n, 0>
{
  enum { value = 1; }
};

我想知道特殊的实例的逐渐增长,如:

Special <8, 3> spl;

因此,我在通用结构定义中插入了以下构造函数:

Special() { cout << "Value, x and y are: " << value << "," << x << "," << y;}

但是,我只打印出最终值为336,8,3。如何全面了解y从3逐渐减少到0?

1 个答案:

答案 0 :(得分:3)

  

但是,我只打印出最终值为336,8,3。如何全面了解y从3逐渐减少到0?

您没有获得预期的输出,因为类本身不会递归地从它们自己派生。构造Special<8,3>时,它不是从Special<7,2>派生的。因此,构造Special<7,2>时,Special<8,3>的构造函数不会被调用。

解决方案1:将类更改为从下一个递归类继承

#include <iostream>

template <unsigned x, unsigned y> struct Special;

template <unsigned x, unsigned y> 
struct Special : Special<x-1, y-1>
{
   Special()
   {
      std::cout << "Value, x and y are: " << value << "," << x << "," << y << std::endl;
   }
   enum { value = x * Special<x-1, y-1> :: value };
};

template <unsigned n>
struct Special<n, 0>
{
   Special()
   {
      std::cout << "Value, x and y are: " << value << "," << n << "," << 0 << std::endl;
   }

   enum { value = 1 };
};

int main()
{
   Special<8,3> s;
}

解决方案2:使用递归函数获取值而不是枚举

获得所需输出的另一种方法是通过递归函数调用而不是类中的enum,并使用代码在函数中生成输出。

#include <iostream>

template <unsigned x, unsigned y>
struct Special
{
   Special() { getValue(); }

   static int getValue()
   {
      int value = x*Special<x-1, y-1>::getValue();
      std::cout << "Value, x and y are: " << value << "," << x << "," << y << std::endl;
      return value;
   }
};

template <unsigned n>
struct Special<n, 0>
{
   static int getValue()
   {
      int value = 1;
      std::cout << "Value, x and y are: " << value << "," << n << "," << 0 << std::endl;
      return value;
   }
};

int main()
{
   Special<8,3> s;
}

两种情况下的输出:

Value, x and y are: 1,5,0
Value, x and y are: 6,6,1
Value, x and y are: 42,7,2
Value, x and y are: 336,8,3