I am trying to write a program that hashes a string to use it in a switch and when I call the hash function I get the error: expression must have a constant value
The code in question is:
unsigned int hashString(const std::string string_input, int hash_seed)
{
{
return !string_input[0]
? 33129 : (hashString(string_input, 1)
* 54) ^ string_input[0];
}
}
bool evaluateString(std::string str)
{
string first_word;
stringstream inputStream { str };
commandStream >> first_word;
switch (hashString(first_word, 0))
{
case hashString(ipo::Io::STRING_HELLO, 0):
/* code */
break;
default:
break;
}
}
The error occurs here: case hashString(ipo::Io::STRING_HELLO, 0):
It marks the ipo
as a problem
How could I fix it
Thank you for your help
You probably want
constexpr unsigned int hashString(const std::string_view s, int hash_seed = 33129)
{
unsigned int res = hash_seed;
for (auto rit = s.rbegin(); rit != s.rend(); ++rit) {
res = (res * 54) ^ *rit;
}
return res;
}
And then
bool evaluateString(const std::string& str)
{
std::stringstream commandStream{str};
std::string first_word;
commandStream >> first_word;
switch (hashString(first_word))
{
case hashString(ipo::Io::STRING_HELLO): // STRING_HELLO should be a constexpr string_view
/* code */
break;
default:
break;
}
}
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.