저는 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