【发布时间】:2020-10-30 16:45:49
【问题描述】:
我想通过原始指针在一组std::unique_ptr 中进行搜索,而不是编写自己的比较器类,我决定使用std::less<> 的透明属性。
这是基于cppreference example 的示例代码。
这不能编译:
#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);
}
虽然这很好用:
#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);
}
FatKey 在这两种情况下都是由 const ref 传递的,它们都是模板类,它们都不是可复制构造的,但仍然只有其中一个有效。
我在这里错过了什么?
【问题讨论】: