"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 { のconstのstd ::文字列fs1x1 = "fs1x1"。 };
問題は、私の場合、ステートメントでは、shs(Pfn::fs1x1)
が定数式ではないことをコンパイラーが報告しているということです。正確なエラーメッセージは次のとおりです。事前にすべてのハッシュ値をうまくして、case文にそれらをハードコーディングすることは本当に退屈だろう
:
ケース値は定数式ではありません。実行時に何とか定数式を作成する方法について提案がありますか?
EDIT:私の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'を追加できますか? –