gpt4 book ai didi

c++ - 在索引处分配 boost::mpl vector_c 元素的惯用方式

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:12:14 25 4
gpt4 key购买 nike

我有

mpl::vector_c<int, 0, 1, 2, 3, 4, 5>

我想“分配”位置 3 的元素,比如说我想将它设置为 30。因此,我必须写一个元函数获取和索引、 vector 和新值并返回修改后的序列。我最终得到了以下解决方案

template <int k, class sequence, class value>
class assign_element
{
typedef typename mpl::begin<sequence>::type begin;
typedef typename mpl::advance<begin, mpl::int_<k> >::type pos;
typedef typename mpl::erase <sequence, pos>::type sequence2;

typedef typename mpl::begin<sequence2>::type begin2;
typedef typename mpl::advance<begin2, mpl::int_<k> >::type pos2;
public:
typedef typename mpl::insert <sequence2, pos2, value>::type type;
};

然后我按如下方式使用它

typedef mpl::vector_c<int, 0, 1, 2, 3, 4, 5> sequence;
typedef typename assign_element<3, sequence, mpl::int_<30> >::type result;

此解决方案有效,但如您所见,它非常复杂(涉及迭代器、高级...)。这个用例是否存在更简单且可能有效的解决方案?提前致谢!

最佳答案

我从未使用过 MPL,但它看起来很有趣,我看了一下文档。这是我的 3 个答案,希望对您有所帮助:

1) 错误的答案 - 然而可能是找到正确答案的良好开端。你考虑使用 replace_if 吗?

typedef vector_c<int, 0, 1, 2, 3, 4, 5> sequence;
typedef replace_if< numbers, equal_to<_,int_<3> >, int_<30> >::type result;

您需要一个 at_pos<3> 谓词。我没有找到这样的,

2) 你的回答是正确的。你封装了它 - 所以用法是一行。在谈论易用性时,用法很重要 - 而不是实现,请考虑采取一些措施从用法行中删除这个烦人的类型名称。也许您的 assign_element<> 应派生自 mpl::insert<>?或者考虑在 C++11 中使用“using”来移除 typedef...

3) 我会推荐最后一个答案:让 MPL 作者添加一些叫做 replace_at 的东西...

喂,彼得·纽约

关于c++ - 在索引处分配 boost::mpl vector_c 元素的惯用方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11048444/

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