Template specialization for a fixed value

3.6k views Asked by At

I am a beginner in c++ templates. i am trying to calculate factorial using templates and attached the code below. I want to replace the if(t==0) section using template specialization but am unalbe to do so till now. Please help
#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;
    }
1

There are 1 answers

0
Dietmar Kühl On BEST ANSWER

First off, you specialization is just wrong: you cannot specialize a template on a parameter expecting a type with a value. You can specialize your Factorial class template on types. For example, you could specialize

template <>
class Factorial<int> {
    ...
};

If you wanted to specialize your template on a value you'd need to make the primary template travel in terms of values, e.g.:

template <int N>
class Factorial { // primary template
    ...
};
template <>
class Factorial<0> { // specialization
    ...
};

Next, your computation is effectively a run-time computation and you can't have the compiler dispatch processing of run-time values to template specializations. If you'd actually wanted to do something like that you'd need to do it programmatically. That is, once you are inside a function you won't be able to have compiler dispatch a function argument to a template specialization. If you want to have the compiler dispatch to a template specialization you'll need to use constant expressions, probably in the form of [static] members of class templates.