Как исправить выражение, которое должно иметь постоянное значение в C ++ - PullRequest
0 голосов
/ 06 мая 2020

Я пытаюсь написать программу, которая хеширует строку для использования ее в переключателе, и когда я вызываю функцию ha sh, я получаю сообщение об ошибке: expression must have a constant value

Рассматриваемый код:

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;
    }


}

Здесь возникает ошибка: case hashString(ipo::Io::STRING_HELLO, 0):

Он отмечает ipo как проблему

Как я могу это исправить

Спасибо Вам за помощь

1 Ответ

0 голосов
/ 06 мая 2020

Вероятно, вы захотите

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;
}

А потом

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;
    }
}
...