gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:30:31 26 4
gpt4 key购买 nike

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

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; }
};

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

Special <8, 3> spl;

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

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

但是,我只将最终值打印为 336、8、3。如何获得 y 从 3 逐渐减少到 0 的全貌?

最佳答案

But, I only got the final values printed as 336, 8, 3. How do I get the full picture of gradual reduction in y from 3 to 0?

您得不到预期的输出,因为类本身不是从它们自身递归派生的。当你构造一个 Special<8,3> , 它不是派生自 Special<7,2> .因此,Special<7,2> 的构造函数构造 Special<8,3> 时不会被调用.

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

#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

关于c++ - 跟踪专用模板对象的枚举成员值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38529395/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com