Is it feasible to use a constexpr hash to calculate enum values and then perform a user-defined conversion?
In the following code, could a constexpr function be used to calculate a hash? Once that is working, would it then be possible to use it in a user-defined conversion?
#include <string>
#include <iostream>
#include <type_traits>
enum class Categories;
#define A 54059 /* a prime */
#define B 76963 /* another prime */
#define C 86969 /* yet another prime */
constexpr std::underlying_type<Categories>::type hash_str(const char* s)
{
//unsigned h = 31 /* also prime */;
//while (*s) {
// h = (h * A) ^ (s[0] * B);
// s++;
//}
//return h; // or return h % C;
return 123;
}
enum class Categories{
CAT_1 = 1, // CAT_1 = hash_str("CAT_1");
CAT_2 = 2, // CAT_2 = hash_str("CAT_2");
CAT_3 = 3, // CAT_3 = hash_str("CAT_3");
CAT_4 = hash_str("CAT_4")
};
int main()
{
std::string category_text = "CAT_4";
int category_string_hash = hash_str(category_text.c_str());
Categories category = (Categories)hash_str(category_text.c_str());
//Categories category2 = (Categories)category_text; // no suitable conversion exists
return 0;
}
Aucun commentaire:
Enregistrer un commentaire