0
我是C++模板的初學者。我正在嘗試使用模板來計算階乘,並附上下面的代碼。我想用模板專業化來取代if(t == 0)部分,但我們現在還沒有做到這一點。請幫助
的#include固定值的模板專業化
template <class T>
class Factorial
{
public:
T factorial(T t)
{
if(t==0)
return 1;
fact[t] = t*factorial(t-1);
std::cout<<"t and fact[t] "<<t<<", "<<fact[t]<<std::endl;
return fact[t];
}
void Print(T t)
{
std::cout<<"fact["<<t<<"] = "<<fact[t]<<std::endl;
}
private:
T fact[100];
};
/*
std::constexpr bool isZero(int x)
{
if(x==0)
return true;
}
*/
template<>
class Factorial<0>
{
public:
int factorial(int x)
{
return 1;
}
void Print(int t)
{
std::cout<<"special fact["<<t<<"] = "<<1<<std::endl;
}
};
int main()
{
Factorial<int> fact;
fact.factorial(5);
fact.Print(4);
return 0;
}
實際上有數千個使用遞歸模板編寫的階乘函數的例子。我建議你首先得到一個工作示例,然後看看在完成這樣的飛行之前如何完成它。 – PaulMcKenzie