【问题标题】:How to write last recursion for meta-programming template in c++如何在 C++ 中为元编程模板编写最后一次递归
【发布时间】:2014-05-23 20:57:07
【问题描述】:

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

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长什么样子?
  • 只是想象的参数。当模板中有两个(或更多)参数时,我很好奇如何在元编程中编写最后一次递归。

标签: c++ templates recursion metaprogramming template-meta-programming


【解决方案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; }
};

【讨论】:

    【解决方案2】:

    如果你的编译器支持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));
    }
    

    【讨论】:

      猜你喜欢
      • 2012-08-29
      • 1970-01-01
      • 1970-01-01
      • 2020-03-20
      • 2021-08-11
      • 1970-01-01
      • 1970-01-01
      • 2016-12-11
      • 1970-01-01
      相关资源
      最近更新 更多