constexpr函数呢?当然,实现该哈希可能会很痛苦。你会有这样的东西:
// maybe another return type
constexpr uint64_t hash_metafunction(const char* input) {
    // replace some_value with the hash implementation
    return some_value;
}
void my_function(char const* string_ptr)
{
  switch (hash_function(string_ptr))
  {
    case hash_metafunction("yoohooo"):
      ...
      break;
    case hash_metafunction("woooooo"):
      ...
      break;
    ...
  }
}
该hash_metafunction函数将在编译时执行。
编辑:这是一个天真的实现,它基本上将输入字符串转换为uint64_t:
constexpr uint64_t do_the_hash(const char* input, uint64_t value_so_far) {
    return *input ? do_the_hash(input + 1, (value_so_far << 8) | *input) : value_so_far;
}
constexpr uint64_t hash_metafunction(const char* input) {
    return do_the_hash(input, 0);
}
现场演示在这里。
编辑:我已经实现了编译时MD5 ,你可以在这里找到源代码。为了使用它,请执行以下操作:
#include <iostream>
#include "md5.h"
int main() {
    constexpr auto value = ConstexprHashes::md5("constexpr rulz");
    std::cout << std::hex;
    for(auto v : value) {
        if(((size_t)v & 0xff) < 0x10)
            std::cout << '0';
        std::cout << ((size_t)v & 0xff);
    }
    std::cout << std::endl;
}
这将打印出哈希:“b8b4e2be16d2b11a5902b80f9c0fe6d6”。