【问题标题】:Using mpl::vector inside metafunction definition在元函数定义中使用 mpl::vector
【发布时间】:2014-05-22 06:27:39
【问题描述】:

我有元函数 FibIter。它计算斐波那契数列中对应于数字(参数 Iter)的斐波那契数。然后我使用 mpl::transform 创建 mpl::vector 斐波那契序列从 0 到 N。我已经编写了代码:

template <typename F1, typename F2, typename Iter>
struct FibIter :
    mpl::if_
    <
        mpl::equal_to <Iter, mpl::int_ <0> >,
        F1,
        FibIter <F2, mpl::plus<F1, F2>, mpl::minus <Iter, mpl::int_ <1> > >
    >::type
{ };

const int N = 22;

typedef mpl::range_c <int, 0, 22> Numbers;

typedef
    mpl::transform
    <
        Numbers,
        FibIter <mpl::int_ <0>, mpl::int_ <1>, mpl::_ >,
        mpl::back_inserter
        <
            mpl::vector <>
        >
    >::type
FibSeq;

但是,这并不好。因为 FibSeq 中的每个数字都从 0 开始一次又一次地计算。 我想在 FibIter 定义中递归地在 FibIter 和 push_back 数字之前创建 mpl::vector 。 我该怎么做?请帮忙。

【问题讨论】:

  • 这是您真正想要的方式吗? mpl::transform 一般用于t -&gt; f(t) 变换,不适合递归序列

标签: c++ templates metaprogramming


【解决方案1】:

MPL 和元编程通常依赖于回溯——您可能已经知道这一点。但是transform 不适合这种情况。提出你的问题,例如。

// Untested!!!!

template<int N>
struct fib {
  // guard against bad N value
  BOOST_STATIC_ASSERT((N > 1));
  // previous f(0:N-1) values
  typedef typename fib<N-1>::vector previous;
  // current value, f(N) = f(N-1) + f(N-2)
  static const int value = (
    mpl::at_c<previous, N-1>::type::value +
    mpl::at_c<previous, N-2>::type::value
  );
  // append f(N) to F(0:N-1)
  typedef typename mpl::push_back<previous, mpl::int_<value> >::type vector;
};

// corner case, N=0
template<>
struct fib<0> {
  static const int value = 0;
  typedef mpl::vector_c<int,0> vector;
};

// corner case, N=1
template<>
struct fib<1> {
  static const int value = 1;
  typedef mpl::vector_c<int,0,1> vector;
};

BOOST_STATIC_ASSERT(( mpl::back< typename fib<10>::vector >::type::value == 55 ));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多