我使用的是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 来访问值映射,并使用.uncertainty来访问不确定性图。
我真的不想使用任何其他的boost库;hana对我的项目来说已经足够了。
发布于 2020-06-26 23:22:22
它通常倾向于使用聚合和继承。
正如"Mooing“在注释中所述,您可以使用一个函数将operator[]转发到values地图。
查看operator[]在Boost.Hana中的实现,您会注意到每种值类型都存在重载,因为无法推断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() { }如果你想使用无聊的,旧的C++17:
https://stackoverflow.com/questions/62599514
复制相似问题