【问题标题】:Boost::Hana tuple, best way to modify a valueBoost::Hana 元组,修改值的最佳方法
【发布时间】:2020-04-15 09:26:35
【问题描述】:

我对这个强大的库很陌生。我很惊讶我找不到一种简单的方法来给定一个元组,返回另一个仅通过索引修改单个元素的元组。

此外,我希望此方法在编译时也可用

例如:

auto tup = hana::make_tuple(1_c,2_c,3_c);
static_assert(modify(tup,1,2000_c) == hana::make_tuple(1_c,2000_c,3_c));

我想我可以通过结合 insert 和 remove_at 来实现这个结果,但我想知道是否有更有效的方法来做到这一点

【问题讨论】:

    标签: c++ tuples boost-hana


    【解决方案1】:

    只是为了让其他可能发现“修改值”意味着更改运行时值的人清楚,hana::athana::at_c 以及相应的 operator[] 可以返回可变引用以更改值运行。这不会改变元素的类型:

    hana::at_c<1>(tup) = 2000;
    

    https://godbolt.org/z/xErFNm

    至于替换元素类型和所有,Boost.Hana 不直接支持这个,但是查看remove_at 的实现,实现replace_at 是直截了当的:

    #include <boost/hana.hpp>
    #include <utility>
    
    namespace hana = boost::hana;
    using namespace hana::literals;
    
    template <typename Xs, typename X, std::size_t ...before, std::size_t ...after>
    constexpr auto replace_at_helper(Xs&& xs, X&&x, std::index_sequence<before...>,
                                          std::index_sequence<after...>) {
      return hana::make_tuple(
          hana::at_c<before>(std::forward<Xs>(xs))...,
          std::forward<X>(x),
          hana::at_c<after + sizeof...(before) + 1>(std::forward<Xs>(xs))...);
    }
    
    template <std::size_t n>
    constexpr auto replace_at_c = [](auto&& xs, auto&& x) {
        constexpr auto len = decltype(hana::length(xs))::value;
        return replace_at_helper(static_cast<decltype(xs)>(xs),
                                 static_cast<decltype(x)>(x),
                                 std::make_index_sequence<n>{},
                                 std::make_index_sequence<len - n - 1>{});
    };
    
    auto tup = hana::make_tuple(1_c,2_c,3_c);
    static_assert(replace_at_c<1>(tup,2000_c) == hana::make_tuple(1_c,2000_c,3_c));
    

    https://godbolt.org/z/H2aySg

    这比组合其他依赖于创建中间元组来打乱值的函数更有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-08
      • 2016-02-28
      • 1970-01-01
      • 2011-01-04
      • 1970-01-01
      • 2010-10-07
      • 2011-11-10
      相关资源
      最近更新 更多