我正在使用库nlohmann/json并希望创建一个unordered_mapof std::stringto nlohmann::json。
#include <nlohmann/json.hpp>
class basic_container {
public:
using key_type = std::string;
using mapped_type = nlohmann::json;
using container_type = std::unordered_map<key_type, mapped_type>;
using reference = typename container_type::reference;
using const_reference = typename container_type::const_reference;
// error: cannot bind non-const lvalue reference to an rvalue
reference at(const key_type &key) {
return data.at(key);
}
// warning: returning reference to temporary
const_reference at(const key_type &key) const {
return data.at(key);
}
// error: cannot bind non-const lvalue reference to an rvalue
reference operator[](const key_type &key) {
return data[key];
}
private:
container_type data;
};
Run Code Online (Sandbox Code Playgroud)
该类nlohmann::json在库中的定义类似于以下内容。
template<...>
class basic_json {};
using json = basic_json<>;
Run Code Online (Sandbox Code Playgroud)
reference我不明白为什么在尝试将 a或 a返回const reference到 a时遇到问题nlohmann::json。上述代码中各部分的完整编译器错误error:概述如下。
error: cannot bind non-const lvalue reference of type 'container::reference' {aka 'std::pair<const std::__cxx11::basic_string<char>, nlohmann::basic_json<> >&'} to an rvalue of type 'std::pair<const std::__cxx11::basic_string<char>, nlohmann::basic_json<> >'
Run Code Online (Sandbox Code Playgroud)
更好的智能感知错误。
a reference of type "container::reference" (not const-qualified) cannot be initialized with a value of type "nlohmann::basic_json<std::map, std::vector, std::string, bool, int64_t, uint64_t, double, std::allocator, nlohmann::adl_serializer, std::vector<uint8_t, std::allocator<uint8_t>>>"
Run Code Online (Sandbox Code Playgroud)
感谢任何帮助。谢谢
编辑:解决方案是正确定义别名。请参阅以下内容。
class basic_container {
public:
using key_type = std::string;
using mapped_type = nlohmann::json;
using container_type = std::unordered_map<key_type, mapped_type>;
// using reference = typename container_type::reference;
// using const_reference = typename container_type::const_reference;
using reference = typename mapped_type::reference;
using const_reference = typename mapped_type::const_reference;
// ...
};
Run Code Online (Sandbox Code Playgroud)
你的包装纸at()等。等人。返回错误的东西。
如果您查找unordered_map::at() 的引用:它会返回对 (const) 的引用T,又名value_type,又名您的mapped_type.
reference/const_reference是完全不同的东西。
同样的问题也会发生在你的operator[]超载上。
PS 避免这种混乱的最简单方法是将返回类型声明为(const 限定的,在适当的情况下)auto &(在本例中)。让您的 C++ 编译器正确处理。