私は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