4 ms·
C++11 compile-time string hashing
- timmytokyo 11y agoI 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.
- daemin 11y agoI don't think it will be as bad as the slowdown caused by template metaprogramming, and according to some compiler vendors that has somewhat been taken care of already.
- Someone 11y agoIf 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.
- Kristine1975 11y agoAnd 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 11y agoHow can you get a compile-time error if some_string has a hash collision?
- Kristine1975 11y agoGood point. You only get a compile-time error if the strings in the switch collide with each other.
- tcbawo 11y agoI'm looking forward for this type of thing making its way into C++ reflection and serialization libraries.