Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truly compile-time string hashing in C++

Basically I need a truly compile-time string hashing in C++. I don't care about technique specifics, can be templates, macros, anything. All other hashing techniques I've seen so far can only generate hashtable (like 256 CRC32 hashes) in compile time, not a real hash.

In other words, I need to have this

printf("%d", SOMEHASH("string"));

to be compiled as (in pseudo-assembler)

push HASHVALUE
push "%d"
call printf

even in Debug builds, with no runtime operations on string. I am using GCC 4.2 and Visual Studio 2008 and I need the solution to be OK for those compilers (so no C++0x).

like image 785
John Avatar asked Jun 23 '11 16:06

John


2 Answers

The trouble is that in C++03 the result of subscripting a string literal (i.e. access a single character) is not a compile-time constant suitable for use as a template parameter.

It is therefore not possible to do this. I would recommend you to write a script to compute the hashes and insert them directly into the source code, i.e.

printf("%d", SOMEHASH("string"));

gets converted to

printf("%d", 257359823 /*SOMEHASH("string")*/ ));

like image 154
Alexander Gessler Avatar answered Oct 24 '22 03:10

Alexander Gessler


Write your own preprocessor that scans the source for SOMEHASH("") and replaces it with the computed hash. Then pass the output of that to the compiler.

(Similar techniques are used for I18N.)

like image 34
Alan Stokes Avatar answered Oct 24 '22 01:10

Alan Stokes