A few nights ago a friend asked me if I had any idea how to make his magic macro work. The general idea behind it was simple: for strings known at the compile time, return type parametrized on the string hash; otherwise return a runtime type. He even provided the type trait he uses to determine if we’re dealing with a string literal. It works well for his case and its potential wrongness is not the point of this article.
The point was something else: let us define a macro NAME and classes Const<size_t> and Runtime, such that the following is valid code:
std::string runtime; std::cin >> runtime; auto c = NAME("KrzaQ"); auto r = NAME(runtime); // 9546715638267443724UL is fnv1a64("KrzaQ"); static_assert(std::is_same<decltype(c), Const<9546715638267443724UL>>{}); static_assert(std::is_same<decltype(r), Runtime<std::string>>{}); |
Always willing to help, I sat down to show him how the C++20 solution would like, then how to do a simple tag-dispatch, and to see if the macro could be replaced with a function call.
Or so I thought.