I have a function that calculates the hash of a string literal:
inline consteval uint64_t HashLiteral(const char* key)
{
// body not important here...
return 0;
}
In another function I need both the literal string, and its hash which I want to have calculated at compile-time:
void function(const char* s)
{
worker(s, HashLiteral(s));
}
It seems however be impossible to make such a call like function("string") and have the hash calculated in its body at compile-time. The best I came up for now is using a macro, and redefine the function:
#define MakeHashParms(s) s,HashLiteral(s)
void function(const char* s, const uint64_t hash)
{
worker(s, hash);
}
function(MakeHashParms("string"));
Is a more straightforward solution possible?
You could modify
functionto accept a "hashed string" structure which can be implicitly constructed from aconst char*. If you make the conversion constructorconsteval, you can guarantee that the hash is always computed at compile time.Try it online on godbolt