156 | | when all the inputs are constant expressions. Indeed empirical testing of clang 3.7 and VS2015 found both currently |
157 | | do '''not''' constexpr execute when the result is not stored constexpr, so in a naive implementation the last |
158 | | statement '''does''' generate a runtime lookup on current compiler technology despite the constant expression inputs. |
159 | | If you'd like to see more detail about this specific problem, have a look at the assembler generated for a toy |
160 | | static_map implementation at https://goo.gl/eO7ooa. |
| 158 | when all the inputs are constant expressions. The outcome therefore depends entirely on which compiler version |
| 159 | you are using and a fair bit of luck - sometimes GCC but not clang will work, sometimes it's the opposite. And |
| 160 | Visual Studio is always a surprise! |
182 | | Write a function which uses one of the compile time string hashing techniques at https://stackoverflow.com/questions/2111667/compile-time-string-hashing |
183 | | (or a constexpr hash function of your preference) to generate a constexpr `std::array<unsigned>` of its input strings. The function ought to have the following |
184 | | prototype: |
185 | | |
186 | | {{{ |
187 | | #!c++ |
188 | | template<class... Strings> constexpr std::array<unsigned, sizeof...(Strings)> hash_strings(Strings&&... strings); |
189 | | |
190 | | // Examples of usage |
191 | | constexpr std::array<unsigned, 0> string_hashes0 = hash_strings(); |
192 | | constexpr std::array<unsigned, 2> string_hashes2 = hash_strings("niall", "douglas"); |
193 | | constexpr std::array<unsigned, 4> string_hashes4 = hash_strings("google", "summer", "of", "code"); |
194 | | // This should fail elegantly and usefully ... |
195 | | //constexpr std::array<unsigned, 0> string_hashes_fail = hash_strings(5); |
196 | | }}} |
197 | | |
198 | | In your submission you should: |
199 | | |
200 | | 1. Explain why you chose the constexpr string hash function you did and the strengths of your choice over other choices. |
201 | | 2. Test that the output is identical whether executed by the compiler at compile time, or at runtime. |
202 | | 3. '''Prove''' that the compile time constexpr implementation generates no runtime code whatsoever. |
| 182 | 1. Persuade the toy static_map implementation at https://goo.gl/eO7ooa to generate the same minimum output |
| 183 | under -O3 optimisation with GCC as it does with clang. Extra bonus points if you can persuade VS2017 to |
| 184 | do the same. You may use C++ 17 features if you find that helps. |