I recently read a blogpost about compile-time string-hashes and constexpr and I’m still not convinced and see no real reason to leave my old and true friend the script :)
So first of lets look at the problem we want to solve. We want a way to do things like this and not pay the runtime cost ( and in this case just compile! ).
void my_func( uint32_t val )
{
switch( val )
{
case HashOfString("some_string"):
do_some_stuff();
break;
case HashOfString("some_other_string"):
do_some_other_stuff();
break;
}
}
Simple enough. What seems to come up over and over again is ways of doing this with the compiler compile-time and now recently just marking HashOfString
as constexpr
and “trust the compiler”.
The solution I usually fall back to is to just have a text-file where each line is hashed with a custom script and written to a .h file with values such as: