I have strings which represent image names like "foobar.png" etc. As you know, switch-case in C++ does not support switching on a string.
I'm trying to work around this, by hashing the string to std::size_t, and then using that value in the switch-case statements.
For example:
//frameName is an std::string which represents foobar.png etc..
switch (shs(frameName)) { //shs is my hash func which returns std::size_t;
case shs(Pfn::fs1x1): //Problem in this line
default:{
break;
}
}
In a separate file (Pfn.hpp):
namespace Pfn{ const std::string fs1x1 = "fs1x1"; };
The problem is, that in my case statement the compiler reports that shs(Pfn::fs1x1)
is not a constant expression. The exact error message is:
Case value is not a constant expression:
It would be really tedious to work out all the hash-values in advance and then hardcode them into the case statements. Do you have a suggestion on how I can somehow create the constant expressions at runtime ?
EDIT: My shs function:
static std::size_t shs(std::string string){
return Hash::shs::hs(string);
}
//...
namespace Hash{
struct shs{
public:
inline std::size_t operator()(const std::string &string)const{
return hashString(string);
}
static std::size_t hs(const std::string &string){
std::size_t seed = 0;
hash_combine(seed,string);
return seed;
}
//From Boost::hash_combine.
template <class T>
static inline void hash_combine(std::size_t& seed, const T& v)
{
std::hash<T> hasher;
seed ^= hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2);
};
};
}