class hash value

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
        //XTSTATIC_HASH_STR: it has been already implemented
        enum {
            STR_hash = XTSTATIC_HASH_STR("STR")/*compile time value*/,
            XXX_hash = XTSTATIC_HASH_STR("XXX")/*compile time value*/
        };


        //class hash's simple implementation
        #define XTSTATIC_HASH_TYPE(type) XTSTATIC_HASH_STR(#type)
        auto vec_int_hash_way1 = XTSTATIC_HASH_TYPE(std::vector<int>);

        using TmpType = std::vector<int, std::allocator<int>>;
        static_assert(std::is_same_v<std::vector<int>, TmpType>);
        auto vec_int_hash_way2 = XTSTATIC_HASH_TYPE(TmpType);


vec_int_hash_way1 and vec_int_hash_way2 will be different!
who can give an XTSTATIC_HASH_TYPE implementation(base on XTSTATIC_HASH_STR) where vec_int_hash_way1 and vec_int_hash_way2 will have the same value.

 
#define XTSTATIC_HASH_TYPE(x) 0 

But in all seriousness, I don't think there's a portable, compile-time solution for this. There's
http://www.cplusplus.com/reference/typeinfo/type_info/name/
http://www.cplusplus.com/reference/typeindex/type_index/
but both use RTTI, they are not evaluated at compile-time. I don't think it's even possible to kludge something together using template metaprogramming. I'm pretty sure to have a general, robust solution you would need help from the compiler.

EDIT: One partial solution I can think of is this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
template <typename T>
struct type_hasher{
    static const int value = -1; //Value for unknown types
};

#define DEFINE_TYPE_HASH_VALUE(t, v) \
template <> \
struct type_hasher<t>{ \
    static const int value = v; \
}

DEFINE_TYPE_HASH_VALUE(int, 1);
DEFINE_TYPE_HASH_VALUE(std::string, 2);
DEFINE_TYPE_HASH_VALUE(std::vector<int>, 3);

#define XTSTATIC_HASH_TYPE(type) (type_hasher<type>::value)

enum TypeHashes{
    Unknown = -1,
    Int = XTSTATIC_HASH_TYPE(int),
    String = XTSTATIC_HASH_TYPE(std::string),
    VectorInt = XTSTATIC_HASH_TYPE(std::vector<int>)
};

struct RandomType{};

int main(){
    std::cout
        << XTSTATIC_HASH_TYPE(int) << std::endl
        << XTSTATIC_HASH_TYPE(std::string) << std::endl
        << XTSTATIC_HASH_TYPE(std::vector<int>) << std::endl
        << XTSTATIC_HASH_TYPE(RandomType) << std::endl
        << XTSTATIC_HASH_TYPE(int **) << std::endl;
}
Last edited on
Topic archived. No new replies allowed.