【发布时间】:2014-12-27 20:44:15
【问题描述】:
我正在使用带有 std::unique_ptr<> 实例的键的 STL 关联容器(std::set 和 std::map)。键定义等价于:
struct Key
{
std::unique_ptr<Object> object;
bool operator== (const Key& rhs) const { return object->equal (*rhs.object); }
bool operator< (const Key& rhs) const { return object->less (*rhs.object); }
}
众所周知,STL 关联容器(尤其是自 C++11 起)无法获得对要从中移动的键的非常量引用。而且我的密钥是不可复制的,所以c++: Remove element from container and get it back 不起作用。
有没有非 UB 方法来解决这个问题?
我目前的解决方案如下:
template <typename T>
using map_pair_type = std::pair<typename T::key_type, typename T::mapped_type>;
template <typename T>
typename T::value_type take_set (T& container, typename T::iterator iterator)
{
typename T::value_type result = std::move (const_cast<typename T::value_type&> (*iterator));
container.erase (iterator);
return result;
}
template <typename T>
map_pair_type<T> take_map (T& container, typename T::iterator iterator)
{
map_pair_type<T> result {
std::move (const_cast<typename T::key_type&> (iterator->first)),
std::move (iterator->second)
};
container.erase (iterator);
return result;
}
【问题讨论】:
-
“有没有非 UB 的方法来解决这个问题?” 没有。N3645 可能会有所帮助,但该提案被拒绝并且没有被重新再次提交。