此代码有效:
class MyObj {};
class MyData {
public:
using tMyMap = std::map<uint64_t, std::shared_ptr<MyObj>>;
const tMyMap& get_normal() const;
const tMyMap& get_reverse() const;
private:
std::map<uint64_t, std::shared_ptr<MyObj>> _normal;
std::map<uint64_t, std::shared_ptr<MyObj>, std::less<uint64_t>> _reverse;
};
const MyData::tMyMap& get_normal() const { return _normal; }
const MyData::tMyMap& get_reverse() const { return _reverse; }
但 clang-tidy 建议我使用透明仿函数并更改 std::less<uint64_t>
至 std::less<>
在我的声明中 _reverse
.不幸的是,当我这样做时,代码不再编译:
test_map.cpp: In member function ‘const tMyMap& MyData::get_reverse() const’:
test_map.cpp:20:60: error: invalid initialization of reference of type ‘const tMyMap& {aka const std::map<long unsigned int, std::shared_ptr<MyObj> >&}’ from expression of type ‘const std::map<long unsigned int, std::shared_ptr<MyObj>, std::less<void> >’
const MyData::tMyMap& MyData::get_reverse() const { return _reverse; }
该错误消息来自 g++,但 clang 给了我一个类似的错误。
为什么有类型的仿函数可以,但透明的仿函数不能编译?
最佳答案
std::map
的默认比较器是 std::less<KeyType>
.
这意味着
std::map<uint64_t, T>
和
std::map<uint64_t, T, std::less<uint64_t>>
是同一类型,但是
std::map<uint64_t, T, std::less<>>
是不同的类型,因为 std::less<uint64_t>
和 std::less<>
是不同的类型。
如果_normal
,你会看到同样的问题和 _reverse
实际上是彼此相反的。我假设你实际上是想声明 _reverse
作为
std::map<uint64_t, std::shared_ptr<MyObj>, std::greater<uint64_t>> _reverse;
所以它的顺序与_normal
相反.
关于c++ - 为什么我不能返回带有透明仿函数的法线贴图引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52461422/