I want to search by raw pointer in a set of std::unique_ptr
, and instead of writing my own comparator class I decided to use the transparent property of std::less<>
.
Here's an example code based on the cppreference example.
This doesn't compile:
#include <memory>
#include <set>
using FatKey = std::unique_ptr<int>;
using LightKey = int;
bool operator<(const FatKey& fk, LightKey* lk) { return fk.get() < lk; }
bool operator<(LightKey* lk, const FatKey& fk) { return lk < fk.get(); }
bool operator<(const FatKey& fk1, const FatKey& fk2) { return fk1.get() < fk2.get(); }
int main()
{
std::set<FatKey, std::less<>> example2;
LightKey lk = 2;
auto search2 = example2.find(&lk);
}
While this works fine:
#include <memory>
#include <set>
template<typename T>
struct UPtrWrapper { std::unique_ptr<T> ptr; };
using FatKey = UPtrWrapper<int>;
using LightKey = int;
bool operator<(const FatKey& fk, LightKey* lk) { return fk.ptr.get() < lk; }
bool operator<(LightKey* lk, const FatKey& fk) { return lk < fk.ptr.get(); }
bool operator<(const FatKey& fk1, const FatKey& fk2) { return fk1.ptr.get() < fk2.ptr.get(); }
int main()
{
std::set<FatKey, std::less<>> example2;
LightKey lk = 2;
auto search2 = example2.find(&lk);
}
The FatKey
is passed by const ref in both cases, they are both template classes, neither of them is copy constructible, but still only one of them works.
What am I missing here?