Can the struct var
have a member std::unordered_map<var, var>
?
Here is a code example that is not compiling because hash<json::var>
is declared after the use of dict json_dict = dict();
:
namespace json
{
struct var;
using dict = std::unordered_map<var, var>;
struct var
{
int integer = 0;
std::string string = "";
dict json_dict = dict();
}
}
namespace std
{
template<> struct hash<json::var>
{
std::size_t operator()(const json::var& k) const
{
return hash<string>()(k.string);
}
};
}
Is there a solution preferably without using pointers?
You can define hash<json::var>::operator()
after you define json::var
itself:
namespace json
{
struct var;
}
namespace std
{
template<> struct hash<json::var>
{
// just a declaration:
std::size_t operator()(const json::var& k) const;
};
}
namespace json
{
using dict = std::unordered_map<var, var>;
struct var
{
int integer = 0;
std::string string = "";
dict json_dict = dict();
};
}
// definition: can access `json::var`'s members
std::size_t std::hash<json::var>::operator()(const json::var& k) const
{
return k.integer;
}
Unrelated, but
string string = "";
dict json_dict = dict();
is equivalent to
string string;
dict json_dict;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.