我正在编写一个哈希函数来帮助加快字符串比较速度。
我的代码库将字符串与许多 const char[]
常量进行比较,如果我可以使用哈希来代替,那就太理想了。我继续将 xxHash 翻译为现代 C++,并且我有一个可以在编译时工作的工作原型(prototype),但我不确定主哈希函数的函数定义应该是什么。
目前,我有这个:
template <size_t arr_size>
constexpr uint64_t xxHash64(const char(data)[arr_size])
{...}
这确实有效,我可以像这样进行编译时调用
constexpr char myString[] = "foobar";
constexpr uint64_t hashedString = xxHash64<sizeof myString>(myString);
[查找最小example here ]
到目前为止一切都很好,但我想为一些养眼的东西添加一个用户定义的文字包装函数,这就是问题所在。
UDL 带有固定原型(prototype),如 specified here
Microsoft 文档规定“此外,任何这些运算符都可以定义为 constexpr”。
但是当我尝试从 constexpr UDL 调用哈希函数时:
constexpr uint64_t operator "" _hashed(const char *arr, size_t size) {
return xxHash64<size>(arr);
}
function "xxHash64" cannot be called with the given argument list
argument types are: (const char*)
这个错误确实有道理。我的函数需要一个字符数组,但它得到一个指针。
但是,如果我要修改 xxHash64 函数的定义以采用 const char *,我就无法再在 constexpr 上下文中工作,因为编译器需要首先解析指针,这在运行时发生。
那么我在这里做错了什么吗,或者这是 UDL 或 constexpr 函数作为一个整体的限制? 再说一遍,我不能 100% 确定顶部的模板化定义是可行的方法,但我不确定如何在编译时从字符串中读取字符。
我不受任何编译器版本或库的限制。如果有更好的方法,请随时提出。
最佳答案
使用constexpr
指针作为常量表达式调用constexpr
函数没有问题
constexpr uint64_t xxHash64(const char* s){return s[0];}
constexpr uint64_t operator "" _g(const char *arr,std::size_t){
return xxHash64(arr);
}
int main()
{
xxHash64("foo");
constexpr auto c = "foobar"_g;
return c;
}
效果很好。
关于c++ - 采用字符数组的 constexpr 函数的正确定义是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74492884/