template function

Patrick Grueger Patrick.Grueger@berlin.de
Sat Mar 13 05:11:00 GMT 1999


Hi, 


>> While compiling this text:
>> ==========================================
>> template<class T,int n> T factorial()
>> {
>>  return factorial<T,n-1>() * T(n);
>> }
>
>> template<class T,int n> T factorial<T,2>()
>> {              // this is line 7
>>  return T(2);
>> }
>
>> int main()
>> {
>>  int a = factorial<int,10>();
>> }
>
>You are defining the same template function twice. I guess you're
>attempting to do partial specialization on a template function. There
>is no such concept.
>
>-- Gaby
>
yes,  i don't have a C++ reference book here but i think the syntax for partial specialization
should look like:

template<class T,int n> T factorial()
{
  return factorial<T,n-1>() * T(n);
}
template<> T factorial<class T,0>()
{   // 0 is a better termination for the recursion
  return 1;
}
int main()
{
  int a = factorial<int,10>();
}

i don't have egcs on the current machine so i can't check this and
MSDev 6.0 doesn't give a correct result on the template function
example and as I think MSDev don't have partial specialization. 
Therefore i can only use a class with a static function and 
following code works:

template<int N> class Factorial{
public:
 static int Foo(){
  return N * Factorial<N-1>::Foo();
 }
};

template<> class Factorial<0>{
public:
 static int Foo(){
  return 1;
 }
};


int main()
{
  long a = Factorial<10>::Foo();
   printf("result is: %i.\n", a);
    a = Factorial<1>::Foo();
   printf("result is: %i.\n", a);
    a = Factorial<0>::Foo();
   printf("result is: %i.\n", a);

   return 0;
}




More information about the Gcc-bugs mailing list