gpt4 book ai didi

c++ - 获取 mpl vector 的前 M 个元素

转载 作者:行者123 更新时间:2023-11-28 01:02:12 26 4
gpt4 key购买 nike

我有一个 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>但无法为 first 找到合适的模板参数和 last . (我使用的是 at_c<...>::type 。)但是,我的理解也是 filter_view也可以用于任务。解决这个问题的最佳方法是什么?

最佳答案

删除是您问题的合理解决方案。

  • 您想要的第一个值是 mpl::begin<T> 的结果这是按您有兴趣返回的元素数量推进的。
  • 你想要的 end 值是 mpl::end<T> 的结果

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

我提供了一个 first_n_elements它采用 MPL 积分常数和 first_n_elements_c它只需要一个整数。

你也可以使用 iterator_range<>如果要使用 View ,请连同下面代码中的 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 ;

};

关于c++ - 获取 mpl vector 的前 M 个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8129325/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com