如何在c++中编写元编程模板的最后递归

How to write last recursion for meta-programming template in c++

本文关键字:编程 递归 最后 c++      更新时间:2023-10-16

我编写了以下元编程模板:

template <unsigned int N, unsigned int P>
struct cutom_imagined
{ 
    static unsigned int function(unsigned int r)
    {
        return (P + N + r) * cutom_imagined<N - 1>::function(r);
    }
};

p实际上就像一个常数。对于上面的例子,我应该如何写最后一个递归?我想应该和下面这个差不多:

template <>
struct cutom_imagined<0, /* What should be here? */ >
{ 
    static unsigned int function(unsigned int) { return 1; }
};

但是不知道怎么写

使P成为模板和专门化的一部分。首先,递归调用是:

return (P + N + r) * cutom_imagined<N - 1, P>::function(r);
第二,专门化现在是局部的:
template <unsigned int P>
struct cutom_imagined<0, P>
{
    static unsigned int function(unsigned int) { return 1; }
};

如果你的编译器支持constexpr,你也可以这样做:

constexpr unsigned int func(unsigned int r, unsigned int p, unsigned int n)
{
  return (n == 0) ? 1 : ((p + n + r) * func(r, p, n - 1));
}