只是为了让其他可能发现“修改值”意味着更改运行时值的人清楚,hana::at 和 hana::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
这比组合其他依赖于创建中间元组来打乱值的函数更有效。