获取mpl矢量的前M个元素

时间:2011-11-14 22:48:46

标签: c++ boost template-meta-programming boost-mpl

我有boost::mpl::vectorN元素,比如说:

typedef boost::mpl::vector<int,float,double,short,char> my_vector;

我希望获得包含M的第一个my_vector元素的序列。因此,如果M为2,我想要一个:

typedef boost::mpl::vector<int,float> my_mvector;

最初我想过使用erase<s,first,last>,但无法为firstlast找出合适的模板参数。 (我使用at_c<...>::type。)但是,我也理解filter_view也可以用于任务。解决这个问题的最佳方式是什么?

1 个答案:

答案 0 :(得分:3)

擦除是解决问题的合理方法。

  • 您想要的第一个值是mpl::begin<T>的结果,它是您有兴趣返回的元素数量的增加。
  • 您希望结束的值是mpl::end<T>
  • 的结果

如果向量中的元素数小于请求的数量,则下面的代码假定您希望元函数返回原始类型。也可以使用静态断言来验证输入整数类型是否小于或等于向量的大小。

我提供了一个first_n_elements,它取一个MPL积分常数,first_n_elements_c只取一个整数。

如果要使用视图,还可以在下面的代码中使用iterator_range<>以及begin和cut迭代器。在这种情况下,我不确定一个优于另一个的优点。

#include <boost/mpl/vector.hpp>
#include <boost/mpl/size.hpp>
#include <boost/mpl/erase.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/less.hpp>
namespace mpl = boost::mpl;



namespace detail 
{
  // Note, this is an internal detail.  Please use the structures below
  template <typename T, typename N>
  struct erase_after_n
  {
    typedef typename mpl::begin<T>::type begin_iter;
    typedef typename mpl::advance<begin_iter, N>::type cut_iter;
    typedef typename mpl::end<T>::type end_iter;

    typedef 
    typename mpl::erase< T,cut_iter, end_iter >::type type;

  };

}


template <typename T, typename N> 
struct first_n_elements
{
  typedef 
  typename mpl::eval_if< mpl::less < mpl::size<T>, N >,
             T,
             detail::erase_after_n<T, N> >::type type;

};

template <typename T, int N> 
struct first_n_elements_c
{
  typedef 
  typename first_n_elements<T, mpl::int_<N> >::type type ;

};
相关问题