编辑:我已经找到并写下了我的问题的解决方案,但我没有回答这个问题,因为我的解决方案可能仍然不理想。
我正在编写一个旨在在 map 的 map 上执行例程的小型库,但我在设计一组类模板时遇到了麻烦,这些模板将使我获得指针或引用(取决于 map 的 value_type 的 second_type)到 map 的 mapped_type,无论 map 的类型如何(例如 std::map、boost::ptr_map)。
为了进一步阐述,我列出了一些输入类型和所需的输出类型。
Case Input Type Output Type
A std::map<int, std::map<int, int> > std::map<int, int>&
B std::map<int, boost::ptr_map<int, int> > boost::ptr_map<int, int>&
C boost::ptr_map<int, std::map<int, int> > std::map<int, int>* const
D std::map<int, std::map<int, int> >* std::map<int, int>&
E std::map<int, boost::ptr_map<int, int> >* boost::ptr_map<int, int>&
F boost::ptr_map<int, std::map<int, int> >* std::map<int, int>* const
我的代码通过了案例 A、B、D 和 E,但在案例 C 和 F 上失败了。这是我目前的情况。
template <class Map>
struct map_utils
{
template <class K>
static typename
boost::remove_pointer<
typename Map::value_type
>::type::second_type&
get(Map& m, const K k)
{
return m[k];
}
template <class K>
static typename
boost::remove_pointer<
typename Map::value_type
>::type::second_type&
get(const Map& m, const K k)
{
return const_cast<Map&>(m)[k];
}
};
template <class Map>
struct map_utils<Map*>
{
template <class T>
static typename
boost::remove_pointer<
typename Map::value_type
>::type::second_type&
get(Map* m, const T t)
{
return (*m)[t];
}
template <class T>
static typename
boost::remove_pointer<
typename Map::value_type
>::type::second_type&
get(const Map* m, const T t)
{
return const_cast<Map*>(m)->operator[](t);
}
};
我正在尝试使用 boost::mpl 来执行此操作,这是我到目前为止所做的,但是我在使用两个版本的代码时遇到了同样的错误。
错误。
error: invalid initialization of reference of type ‘std::map<int, double>* const&’ from expression of type ‘boost::ptr_container_detail::reversible_ptr_container<boost::ptr_container_detail::map_config<std::map<int, double>, std::map<int, void*, std::less<int>, std::allocator<std::pair<const int, void*> > >, true>, boost::heap_clone_allocator>::Ty_’
结构的修改特化处理不是指向映射的指针的左值。
template <class K>
static typename
boost::mpl::if_<
boost::is_pointer<
typename boost::remove_pointer<
typename Map::value_type
>::type::second_type
>,
typename boost::remove_pointer<
typename boost::remove_const<
typename Map::value_type
>::type
>::type::second_type,
typename boost::remove_pointer<
typename Map::value_type
>::type::second_type&
>::type
get(Map& m, const K k)
{
return m[k];
}
最佳答案
C 和 F 似乎是错误的,映射类型不是 boost::ptr_map。否则听起来你可以只使用完整的模板特化来决定它是 std::map 还是 boost::ptr_map。像这样:
template <class Map>
class Whatever;
template <class K, class V>
class Whatever<std::map<K, V> >
{
public:
typedef V& Type;
};
template <class K, class V>
class Whatever<std::map<K, V>* >
{
public:
typedef V& Type;
};
template <class K, class V>
class Whatever<boost::ptr_map<K, V> >
{
public:
typedef V* const Type;
};
template <class K, class V>
class Whatever<boost::ptr_map<K, V>* >
{
public:
typedef V* const Type;
};
关于c++ - 从任意映射中获取对 mapped_type 的指针或引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7219615/