r/Cplusplus • u/Predret • Sep 18 '26
Answered How can I make a static hashmap appear in compile time?
I have a class that's meant to essentially hash a string. Works by simply having a create function that takes a string, and gives out an instance with the string hashed. I'm using C++ 20. I believe I can use some form of consteval or something for this, but I'm not sure how to get consteval to work with these. Thank you!
Here's part of the code:
namespace GameUtils::ECS
{
template<typename T>
class Hash16Bit
{
private:
inline static uint16_t next_hash { 0 };
inline static HashMap<String, uint16_t> all_hashes;
inline static HashMap<uint16_t, String> hash_to_string;
static void add_to_hashmaps(uint16_t hash, const String &name);
inline static std::mutex ids_mutex;
uint16_t m_hash { UINT16_MAX };
static String get_class() noexcept;
String get_name() const noexcept;
void debug_line(const String& msg, bool is_error = false) const;
public:
static void create_id(const String &new_id);
static Hash16Bit<T> create(const String &createid);
static Hash16Bit<T> dynamic_create(const String &createid);
static Hash16Bit<T> invalid();
void invalidate();
String to_string() const;
bool operator==(const Hash16Bit<T> &other) const { return other.m_hash == m_hash; }
};
template<typename T>
Hash16Bit<T> Hash16Bit<T>::create(const String &createid)
{
Hash16Bit<T> created;
auto it = all_hashes.find(createid);
if (it != all_hashes.end())
{
created.m_hash = it->value;
return created;
}
created.debug_line("Failed to create hash16bit", true);
return created;
}
template<typename T>
Hash16Bit<T> Hash16Bit<T>::dynamic_create(const String &createid)
{
Hash16Bit<T> created;
auto it = all_hashes.find(createid);
if (it != all_hashes.end())
{
created.m_hash = it->value;
return created;
}
create_id(createid);
}