std::unordered_set
has a template find
function in C++20. To make it work I define a custom hash and a custom equality compares as follows:
struct BotSettings
{
std::string type;
std::string name;
bool started;
};
namespace helpers
{
struct BotSettingsEqualTo
{
using is_transparent = void;
bool operator() (const BotSettings& left, const BotSettings& right) const
{
return left.name == right.name;
}
bool operator() (const BotSettings& val, const std::string& name) const
{
return val.name == name;
}
bool operator() (const BotSettings& val, const std::string_view& name) const
{
return val.name == name;
}
bool operator() (const BotSettings& val, const char* name) const
{
return val.name == name;
}
bool operator() (const std::string& name, const BotSettings& val) const
{
return val.name == name;
}
bool operator() (const std::string_view& name, const BotSettings& val) const
{
return val.name == name;
}
bool operator() (const char* name, const BotSettings& val) const
{
return val.name == name;
}
};
struct BotSettingsHash
{
using is_transparent = void;
using hash_type = std::hash<std::string_view>;
size_t operator()(const BotSettings& bs) const
{
return hash_type{}(bs.name);
}
size_t operator()(const std::string& txt) const
{
return hash_type{}(txt);
}
size_t operator()(std::string_view txt) const
{
return hash_type{}(txt);
}
size_t operator()(const char* txt) const
{
return hash_type{}(txt);
}
};
}
int main()
{
std::unordered_set<BotSettings, helpers::BotSettingsHash, helpers::BotSettingsEqualTo> set;
set.find(BotSettings{});
set.find(std::string_view("abc"));
set.find(std::string("abc"));
set.find("abc");
return 0;
}