带有原始指针的唯一指针.at()的映射

Blu*_*jay 1 c++ dictionary pointers std unique-ptr

说我有一张地图:

std::map<std::unique_ptr<SomeType>, SomeOtherType> map;
Run Code Online (Sandbox Code Playgroud)

显然,这是行不通的,因为我们地图的键值是唯一的ptr,而不是原始的:

//a pointer from somewhere else in the code
SomeType* p = ...;
auto result {map.at(p)};
Run Code Online (Sandbox Code Playgroud)

相反,可以使用std :: unique_ptr.get()执行以下操作:

SomeType* p = ...;
for(auto& entry : map) {
    if(entry.first.get() == p) {
        //do whatever
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,这是一种非常丑陋且可能效率不高的方法。我的问题很简单,在这种情况下是否有某种方式可以使用.at()函数。

Cal*_*eth 6

在C ++ 14中,您可以提供一个透明的比较器

template<typename T>
struct PtrCompare
{
    std::less<T*> less;
    using is_transparent = void;
    bool operator()(T* lhs, const std::unique_ptr<T> & rhs) const { return less(lhs, rhs.get()); }
    bool operator()(const std::unique_ptr<T> & lhs, T* rhs) const { return less(lhs.get(), rhs); }
    bool operator()(const std::unique_ptr<T> & lhs, const std::unique_ptr<T> & rhs) const { return less(lhs.get(), rhs.get()); }
}

std::map<std::unique_ptr<SomeType>, SomeOtherType, PtrCompare<SomeType>> map;
Run Code Online (Sandbox Code Playgroud)

这样做无济于事at,但可以让您find基于可以比较的任何内容

SomeType* p = ...;
if (auto it = map.find(p))
{
    // use it->second
}
else
{
    throw std::out_of_range;
}
Run Code Online (Sandbox Code Playgroud)