gpt4 book ai didi

c++ - 如何包装(组成)Boost Hana映射并访问括号运算符(operator [])?

转载 作者:行者123 更新时间:2023-12-01 14:52:11 27 4
gpt4 key购买 nike

我正在使用hana map (使用hana::make_map创建)。我有一个非常简单的类,它将继承自hana map ,并公开第二张 map


auto values = hana::make_map( ... );
auto uncertainties = hana::make_map( ... );

template< typename Values, typename Uncertainty >
struct map: Values{
Uncertainty uncertainty;
constexpr map(Values v, Uncertainty u ):
Values( v ),
uncertainty( u )
{ }
};

auto data = map( values, uncertainties );

// I want to do the following

auto hbar = data[ hbar ]; // Type hbar defined elsewhere
auto hbar_u = data.uncertainty[ hbar ]
这曾经工作。我最近更新了Boost Hana的版本,现在出现以下编译器错误:
map.hpp:2:13: error: base
'map_impl' is marked 'final'
struct map: Values{
^

如果我正确理解此消息,则已经明确标记了boost hana,以便我不再继承。
我真正想做的是使用operator[]访问值图,并使用.uncertainty访问不确定性图。 我该怎么做?
我真的不想使用任何其他Boost库。对于我的项目而言,hana绰绰有余。

最佳答案

通常首选使用聚合vs继承。
正如评论中提到的“鸭子”,您可以使用函数转发operator[]values映射。
查看Boost.Hana中operator[]的实现,您会注意到每种值类型都有一个重载,因为无法推导this。 (他们应该解决此问题)
values转换为适当的引用类型将允许您返回正确值类型的引用(如果需要)。这将使其行为完全类似于hana::map

#define BOOST_HANA_CONFIG_ENABLE_STRING_UDL 1
#include <boost/hana.hpp>

namespace hana = boost::hana;
using namespace hana::literals;

template <typename Values, typename Uncertainty>
struct my_map_t {
Values values;
Uncertainty uncertainty;

constexpr decltype(auto) operator[](auto&& key) & {
return static_cast<Values&>(values)[
std::forward<decltype(key)>(key)];
}
constexpr decltype(auto) operator[](auto&& key) && {
return static_cast<Values&&>(values)[
std::forward<decltype(key)>(key)];
}
constexpr decltype(auto) operator[](auto&& key) const& {
return static_cast<Values const&>(values)[
std::forward<decltype(key)>(key)];
}
};

// Note: Clang 10 does not provide implicit deduction guides yet

constexpr auto values = hana::make_map(
hana::make_pair("foo"_s, 42)
);

constexpr auto uncertainties = hana::make_map(
hana::make_pair("bar"_s, 5)
);


constexpr auto my_map = my_map_t(values, uncertainties);

static_assert(my_map["foo"_s] == 42);
static_assert(my_map.uncertainty["bar"_s] == 5);

int main() { }
https://godbolt.org/z/XVNsy-

如果您想使用无聊的旧C++ 17:
https://godbolt.org/z/i-NZd6

关于c++ - 如何包装(组成)Boost Hana映射并访问括号运算符(operator [])?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62599514/

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