如何包装(撰写)增强 hana 地图并访问括号运算符(运算符 [])?
How to wrap (compose) a boost hana map and access the bracket operator (operator[])?
我正在使用hana地图(使用hana::make_map
创建(。我有一个非常简单的类,它将继承自 hana 地图,并公开第二个地图
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 对于我的项目来说绰绰有余。
通常首选使用聚合与继承。
正如"Mooing Duck"在评论中所说,您可以使用一个功能转发values
地图的operator[]
。
查看 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
相关文章:
- 运行时多态性 - 箭头运算符访问了错误的成员?
- 如果键不存在,使用 [] 运算符访问 STL Map 元素会添加新元素
- 通过 [] 运算符访问unordered_map时出错
- 为什么我不能使用 [] 运算符访问 nlohmann C++ JSON 库中的数组?
- 如何使用运算符 [] 访问结构的指定字段值
- 为什么在递增后使用 [] 运算符访问指针数组会返回错误地址的当前内存位置
- 如何使用字符串字符数组中的 ++ 运算符访问下一个字符串
- 将对象数限制为1可以使用点运算符访问静态成员的1
- 提升:使用运算符 [] 访问 bimap
- 为什么默认情况下使用 [ ] 运算符访问超出范围的矢量元素时,C++检测?
- 如何使用 offset 运算符访问字符串的字符,并且字符串位于字符串向量中
- 如何在 vim 中将访问时的向量转换为运算符 [ ] 访问
- 在C++中,我可以使用箭头运算符访问另一个运算符吗
- 无法使用运算符 [] 访问二维堆向量的元素
- 在指向 wstring 的指针上使用 [ ] 运算符访问元素
- 使用作用域运算符访问非静态成员变量
- 使用运算符[]访问一个函数中的字符串会影响C++中另一个函数的输出
- 何时使用 " . " 或 " -> " 运算符访问属性或成员函数?
- 通过运算符 [] 访问静态成员unordered_map
- 试图使用运算符[]访问std::map元素时编译器错误