【发布时间】:2017-04-04 10:16:59
【问题描述】:
我有代表图像名称的字符串,例如“foobar.png”等。 如您所知,C++ 中的 switch-case 不支持切换字符串。
我正在尝试解决这个问题,方法是将字符串散列到 std::size_t,然后在 switch-case 语句中使用该值。
例如:
//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;
}
}
在单独的文件 (Pfn.hpp) 中:
命名空间 Pfn{ 常量 std::string fs1x1 = "fs1x1"; };
问题是,在我的 case 语句中,编译器报告 shs(Pfn::fs1x1) 不是常量表达式。确切的错误信息是:
case 值不是常量表达式:
提前计算出所有哈希值然后将它们硬编码到 case 语句中会非常乏味。您对我如何在运行时以某种方式创建常量表达式有什么建议吗?
编辑:我的 shs 函数:
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);
};
};
}
【问题讨论】:
-
你能添加你的函数
shs吗?