使用C++模板元函数在编译时可以进行任何计算.因此,我正在考虑,如果可能的话:
void my_function(char const* string_ptr)
{
switch (hash_function(string_ptr))
{
case hash_metafunction<"yoohooo">::value:
...
break;
case hash_metafunction<"woooooo">::value:
...
break;
...
}
}
Run Code Online (Sandbox Code Playgroud)
您能否为哈希函数和模板元函数找到代码(库)的位置.如果没有这样的库存在,你能给出一些关于我如何自己滚动模板元函数的提示吗?我特别担心char const*模板元函数的参数.也许一些预处理器魔术可能吗?
一个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;
...
}
}
Run Code Online (Sandbox Code Playgroud)
该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);
}
Run Code Online (Sandbox Code Playgroud)
现场演示这里.
编辑:我已经实现了编译时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;
}
Run Code Online (Sandbox Code Playgroud)
这打印出哈希:"b8b4e2be16d2b11a5902b80f9c0fe6d6".
| 归档时间: |
|
| 查看次数: |
553 次 |
| 最近记录: |