首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何包装(撰写)一个boost hana映射并访问括号操作符(operator[])?

如何包装(撰写)一个boost hana映射并访问括号操作符(operator[])?
EN

Stack Overflow用户
提问于 2020-06-26 17:00:44
回答 1查看 185关注 0票数 2

我使用的是hana地图(使用hana::make_map创建)。我有一个非常简单的类,它将继承hana映射,并公开第二个映射。

代码语言:javascript
复制
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的版本,现在我得到了以下编译器错误:

代码语言:javascript
复制
map.hpp:2:13: error: base
      'map_impl' is marked 'final'
struct map: Values{
            ^

如果我正确理解了这条信息,boost hana已经被显式标记,这样我就不能再继承了。

我真正想要做的是使用operator[] .uncertainty 来访问值映射,并使用.uncertainty来访问不确定性图。

我真的不想使用任何其他的boost库;hana对我的项目来说已经足够了。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-26 23:22:22

它通常倾向于使用聚合和继承。

正如"Mooing“在注释中所述,您可以使用一个函数将operator[]转发到values地图。

查看operator[]在Boost.Hana中的实现,您会注意到每种值类型都存在重载,因为无法推断this。(他们应该解决这个问题)

values转换为适当的引用类型将允许您在需要时返回正确值类型的引用。这将使它的行为与hana::map完全一样。

代码语言:javascript
复制
#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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62599514

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档