[编程][C++] 在Switch-Case中使用字符串!

众所周知,switch中是不支持字符串的,但是通过一些编译时的小技巧,就能方便地实现这个功能!

上代码(


#include <cstdint>

typedef std::uint64_t hash_t;

constexpr hash_t prime = 0x100000001B3ull;
constexpr hash_t basis = 0xCBF29CE484222325ull;

// Compute the hash of a string.
hash_t hash_(char const* str) {
  hash_t ret{basis};

  while (*str) {
    ret ^= *str;
    ret *= prime;
    str++;
  }

  return ret;
}

constexpr hash_t hash_compile_time(char const* str, hash_t last_value = basis) {
  return *str ? hash_compile_time(str + 1, (*str ^ last_value) * prime)
              : last_value;
}

如此一来,编译器能在编译时把字符串转化为hash值,达到直接用字符串作为switch的参数的效果,而不需要再使用各种映射了!

使用方法如下:

  // Jump to real main function
  switch (hash_(currentProgname.c_str())) {
    case hash_compile_time("lsbom"):
      // return main_lsbom(argc, argv);
      std::cout << "Not implemented yet!";
      return 0;
    case hash_compile_time("uninstaller"):
      // return main_uninstaller(argc, argv);
      std::cout << "Not implemented yet!";
      return 0;
    case hash_compile_time("pkgutil"):
      // return main_pkgutil(argc, argv);
      std::cout << "Not implemented yet!";
      return 0;
    case hash_compile_time("installer"):
      return main_installer(argc, argv);
    default:
      std::cout << "Not implemented yet!";
      return 0;
  }

本文以 CC 4.0 BY-SA 版权协议发布。

代码部分以 MIT 协议发布。

参考资料来源:

  1. YoziDream, 使用C++11新特性,实现用字符串作为switch的case子句, CSDN, accessed 26/08/2024
3 个赞