compile-time string hashing

前端 未结 4 521

I need to use a string as the ID to obtain some object. At implement this in a run-time, and works well. But this makes the static type checking impossible, for obvious rea

4条回答
  •  不知归路
    2020-12-31 10:38

    Solution with gcc-4.6:

    #include 
    template
    struct hash_calc {
        static constexpr size_t apply (const char (&s)[N]) {
           return  (hash_calc::apply(s) ^ s[I]) * 16777619u;
        };
    };
    
    template
    struct hash_calc {
        static constexpr size_t apply (const char (&s)[N]) {
           return  2166136261u;
        };
    };
    
    template
    constexpr size_t hash ( const char (&s)[N] ) {
        return hash_calc::apply(s);
    }
    
    int main() {
       char a[] = "12345678";
       std::cout << std::hex << hash(a) << std::endl;
       std::cout << std::hex << hash("12345678") << std::endl;
    }
    

    http://liveworkspace.org/code/DPObf

    I`m happy!

提交回复
热议问题