Hal*_*far 5 c++ compiler-construction hash
使用GCC 4.4(通常是Android和IOS的最大可用)有一种方法可以对字符串进行编译时散列.
我们有一个资源管理器,它将字符串键映射到资源.虽然查找速度很快,但散列和字符串创建速度很慢.就像是:
ResourcesManager::get<Texture>("someKey");
Run Code Online (Sandbox Code Playgroud)
花费大量时间分配字符串"someKey"然后散列它.
我想知道是否有一个技巧可以在编译时使用它来散列它.
您必须实现正确的散列算法,但这可以使用C++ 11的constexpr函数:
#include <iostream>
// Dummy hashing algorithm. Adds the value of every char in the cstring.
constexpr unsigned compile_time_hash(const char* str) {
// Modify as you wish
return (*str == 0) ? 0 : (*str + compile_time_hash(str + 1));
}
int main() {
unsigned some_hash = compile_time_hash("hallou");
std::cout << some_hash << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
然后你可以有一个重载ResourcesManager::get取得compile_time_hash(在这种情况下是无符号)的结果.
这显然取决于您正在应用的散列算法.使用constexpr实现SHA*之类的东西会非常痛苦.
请注意,您需要GCC> = 4.6或clang> = 3.1才能使用constexpr.