固定值的模板特化

Dhe*_*raj 1 c++ templates specialization

我是 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;
    }
Run Code Online (Sandbox Code Playgroud)

Die*_*ühl 5

首先,您的专业化是错误的:您不能在需要具有值的类型的参数上专业化模板。您可以将Factorial类模板专门用于类型。例如,您可以专攻

template <>
class Factorial<int> {
    ...
};
Run Code Online (Sandbox Code Playgroud)

如果您想在某个值上专门化您的模板,则需要根据值使主模板旅行,例如:

template <int N>
class Factorial { // primary template
    ...
};
template <>
class Factorial<0> { // specialization
    ...
};
Run Code Online (Sandbox Code Playgroud)

接下来,您的计算实际上是一个运行时计算,您不能让编译器将运行时值的处理分派到模板特化。如果您确实想做类似的事情,则需要以编程方式进行。也就是说,一旦您进入函数内部,您将无法让编译器将函数参数分派给模板特化。如果您想让编译器分派到模板专业化,您将需要使用常量表达式,可能以static类模板的 [ ] 成员的形式。