I want to write a function evaluated at compile time, it takes a pointer to 4 bytes array, and outputs an int that has the same bit pattern as that array. So I came up with:
constexpr int f(const char* p) {
return *reinterpret_cast<int*>(p);
}
Then, I want to use f()
like this:
switch(x) {
case f("GOOG"):
// do something
case f("MSFT"):
// do something
case f("NIKE"):
// do something
}
However, I got a compiler error:
error: accessing value of ‘"GOOG"’ through a ‘int’ glvalue in a constant expression case f("GOOG")
- How to fix
f()
so it compiles? - Is there a better way to accomplish the same goal?