但是,我只得到最終值打印爲336,8,3。我如何獲得y從3逐漸減少到0的完整圖像?
由於類本身不會從它們自身遞歸地派生,所以不會得到預期的輸出。當您構建Special<8,3>
時,它不是從Special<7,2>
派生的。因此,當您構建Special<8,3>
時,Special<7,2>
的構造函數不會被調用。
解決方法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
抓鬥一張紙。在你寫的第一行,'value = 8 * Special <7, 2> :: value'。在下一行你寫'value = 7 * Special <6, 1> :: value'等等。然後,當你到達最後一行時(當'y'爲零且'value'爲'1'時),然後返回並使用之前行的結果來完成方程。 –
...然後使其成爲「靜態constexpr int」成員,或者甚至更好的函數。 –
@JoachimPileborg:所以,當你被要求編寫一個程序來查找98 * 999的結果時,你抓起一張紙,在第一行寫98,在第二行寫98,...... 98在第999行並垂直添加它們,對吧?誰說書呆子缺乏幽默感? –