Just because there are so many answers saying you can't, I'm going to tell you -- you sure can! With some caveats of course.
constexpr unsigned long encode_(unsigned long in, const char* s)
{
return *s ? encode_((in << 8) | s[0], s + 1) : in;
}
constexpr unsigned long encode(const char* s)
{
return encode_(0, s);
}
constexpr unsigned long operator"" _x(const char* s, long unsigned len)
{
return encode(s);
}
int main(int argc, char **argv)
{
auto x = "hello"_x;
switch (x)
{
case "ola"_x:
break;
case "hello"_x:
break;
}
}
What this code does is it stuffs the characters of your string name into a long integer. This solution is only guaranteed to work for strings of upto 8 characters on a 64-bit system. After that the encoded numbers won't be guaranteed to be unique. To safeguard against inadvertent use of a longer string, I would recommend checking the len argument in the user-defined literal function and causing a compilation error if a longer string is used. Or you can tweak the code a bit and require that the first 8 characters of each string should be unique.
It should be relatively easy to extend my code to the case of 5 bits per lower case english character to increase the length of strings you can use to 13 from 8.
Shannon showed that the english language uses between 0.6 and 1.3 bits per letter in ordinary text. So a 64-bit integer can potentially store about a string of about 64 characters. Such a compression function is not easy to write as a constexpr function, but would be an interesting exercise.