是否可以将哈希值作为编译时常量?

Zeb*_*ish 6 c++ hash compile-time-constant

我以为我会尝试通过散列来选择不同的选项作为字符串,但这不起作用:

#include <type_traits>
#include <string>

inline void selectMenuOptionString(const std::string& str)
{
    switch (std::hash<std::string>()(str))
    {
    case std::hash<std::string>()(std::string("Selection one")) : break; 
        // Expression must have a constant value
    }
}

inline void selectMenuOptionString2(const std::string& str)
{
    size_t selectionOneHash = std::hash<std::string>()(std::string("Selection one"));

    switch (std::hash<std::string>()(str))
    {
    case selectionOneHash: // Expression must have a constant value 
                           // The variable of selectionOneHash cannot be used as a constant
    }

    constexpr size_t hash = std::hash<int>()(6); // Expression must have a constant value
}
Run Code Online (Sandbox Code Playgroud)

似乎我无法在编译时获取哈希值.根据我的阅读,每次不同的输入应该每次产生相同的唯一输出,碰撞的可能性非常低.鉴于这些属性无法在编译时计算哈希值?我对哈希很不了解,我通常使用unordered_map,但我想尝试新的东西以便学习.

Jus*_*tin 10

std::hash::operator()不是constexpr,所以你不能只使用它.相反,您必须编写自己的constexpr哈希函数.例如,以下是FNV-1a哈希算法(未经测试):

template <typename Str>
constexpr size_t hashString(const Str& toHash)
{
    // For this example, I'm requiring size_t to be 64-bit, but you could
    // easily change the offset and prime used to the appropriate ones
    // based on sizeof(size_t).
    static_assert(sizeof(size_t) == 8);
    // FNV-1a 64 bit algorithm
    size_t result = 0xcbf29ce484222325; // FNV offset basis

    for (char c : toHash) {
        result ^= c;
        result *= 1099511628211; // FNV prime
    }

    return result;
}
Run Code Online (Sandbox Code Playgroud)

然后你可以使用它:

int selectMenuOptionString(const std::string& str)
{
    switch (hashString(str))
    {
    case hashString(std::string_view("Selection one")): return 42; 
    default: return 0;
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,如果您编写hashString("Selection one"),它实际上也会散列空终止符,因此您可能希望有一个重载来捕获字符串文字,例如:

template <size_t N>
constexpr size_t hashString(char const (&toHash)[N])
{
    return hashString(std::string_view(toHash));
}
Run Code Online (Sandbox Code Playgroud)

演示


Lig*_*ica -1

您无法在编译时获取运行时值的哈希值,不。

即使您传递了std::hash一个常量表达式,它也没有被定义为能够在编译时执行其哈希工作。

据我所知(这并不远),你必须想出一些可怕的模板元黑客(或者更糟糕的是宏!)来做到这一点。就我个人而言,如果您的文本输入在构建时已知,我只会在代码外部预生成一个哈希值,也许是在某些 Python 驱动的预构建步骤中。