
C++11 compile-time string hashing - ingve
http://www.elbeno.com/blog/?p=1254
======
Kristine1975
And in C++14 you can do away with the recursion and just use a `for` loop.

Compile-time hashing of strings can be used to create a string-switch:

    
    
      constexpr unsigned int hash(const char* string)
      {
        // hash the string
        ...
      }
    

And then:

    
    
      switch(hash(some_string))
      {
         case hash("Hacker News"):
           break;
    
         case hash("Y-Combinator"):
           break;
    
         default:
           break;
      }
    

If there is a collision, you get a compile-time error due to a duplicate
`case`.

~~~
lokedhs
How can you get a compile-time error if some_string has a hash collision?

~~~
Kristine1975
Good point. You only get a compile-time error if the strings in the switch
collide with each other.

------
timmytokyo
I fear the havoc widespread use of constexpr meta-programming could wreak on
compile speed. A few such declarations have no noticeable impact on compile
times, but as the project grows and such declarations start to proliferate,
you can easily imagine productivity suffering due to slow compiles.

In my opinion, techniques like these fall under the category of "interesting
but probably best avoided in production". Kind of like ray-tracers written
with template meta-programming.

~~~
Someone
If that becomes a problem, I think it is fairly easy (certainly easier than
with template metaprogramming) to move the constexpr code into a separate
compilation unit, and let your _make_ handle that problem.

------
tcbawo
I'm looking forward for this type of thing making its way into C++ reflection
and serialization libraries.

