编译时间字符串散列 [英] compile-time string hashing

查看:167
本文介绍了编译时间字符串散列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用一个字符串作为ID来获得一些对象。在运行时实现这一点,并且效果很好。但是这使得静态类型检查是不可能的,原因是显而易见的。

我GOOGLE的算法计算字符串的哈希总和在编译时:的 C ++编译时字符串Boost.MPL 散列。

这似乎是我的问题的最佳解决方案,除了SRING这是必要的算法应该由4个字符被分割为块,或字符逐字符,以及,出于明显的原因。

即,而不是ID的通常的当前记录,我会写这样的:

  hash_cstring<提高:: MPL ::字符串<'OBJE','ct.m','etho','D'>> ::值

这是绝对不能使用的。

现在的问题是,如何正确的字符串传递,如的object.method这个算法?

感谢大家。


解决方案

用gcc-4.6解决方案:

 的#include<&iostream的GT;
模板<为size_t N,为size_t I = 0>
结构hash_calc {
    静态constexpr SIZE_T申请(为const char(安培; S)[N]){
       回报(hash_calc< N,I + 1> ::申请(S)^ S [I])* 16777619u;
    };
};模板<为size_t N'GT;
结构hash_calc< N,N> {
    静态constexpr SIZE_T申请(为const char(安培; S)[N]){
       返回2166136261u;
    };
};模板<为size_t N'GT;
constexpr为size_t哈希(为const char(安培; S)[N]){
    返回hash_calc< N> ::申请(S);
}诠释主(){
   所以char a [] =12345678;
   性病::法院LT&;<性病::十六进制<<哈希(一)LT;<的std :: ENDL;
   性病::法院LT&;<性病::十六进制<<哈希(12345678)<<的std :: ENDL;
}

http://liveworkspace.org/$c$c/DPObf

我真的快乐!

I need to use a string as the ID to obtain some object. At implement this in a run-time, and works well. But this makes the static type checking impossible, for obvious reasons.

I've Googled for the algorithm for calculating the hash-sum of string in the compile-time: C++ compile-time string hashing with Boost.MPL.

It seems to be the perfect solution to my problem, except that the sring which is necessary to the algorithm should be split into pieces by 4 characters, or character-by-character, as well, for obvious reasons.

i.e., instead of the usual current record of the ID's, I'll have to write this way:

hash_cstring<boost::mpl::string<'obje', 'ct.m', 'etho', 'd'>>::value

This is absolutely unusable.

The question is, how to pass correctly the string such as "object.method" to this algorithm?

Thank you all.

解决方案

Solution with gcc-4.6:

#include <iostream>
template<size_t N, size_t I=0>
struct hash_calc {
    static constexpr size_t apply (const char (&s)[N]) {
       return  (hash_calc<N, I+1>::apply(s) ^ s[I]) * 16777619u;
    };
};

template<size_t N>
struct hash_calc<N,N> {
    static constexpr size_t apply (const char (&s)[N]) {
       return  2166136261u;
    };
};

template<size_t N>
constexpr size_t hash ( const char (&s)[N] ) {
    return hash_calc<N>::apply(s);
}

int main() {
   char a[] = "12345678";
   std::cout << std::hex << hash(a) << std::endl;
   std::cout << std::hex << hash("12345678") << std::endl;
}

http://liveworkspace.org/code/DPObf

I`m happy!

这篇关于编译时间字符串散列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆