Compile-time constant id

前端 未结 16 2154
不知归路
不知归路 2020-12-02 20:06

Given the following:

template
class A
{
public:
    static const unsigned int ID = ?;
};

I want ID to generate a unique c

16条回答
  •  温柔的废话
    2020-12-02 20:22

    Here is a C++ code that uses __DATE__ and __TIME__ macro to get unique identifiers for types

    Format:

    // __DATE__ "??? ?? ????"
    // __TIME__ "??:??:??"
    

    This is a poor quality hash function:

    #define HASH_A 8416451
    #define HASH_B 11368711
    #define HASH_SEED 9796691    \
    + __DATE__[0x0] * 389        \
    + __DATE__[0x1] * 82421      \
    + __DATE__[0x2] * 1003141    \
    + __DATE__[0x4] * 1463339    \
    + __DATE__[0x5] * 2883371    \
    + __DATE__[0x7] * 4708387    \
    + __DATE__[0x8] * 4709213    \
    + __DATE__[0x9] * 6500209    \
    + __DATE__[0xA] * 6500231    \
    + __TIME__[0x0] * 7071997    \
    + __TIME__[0x1] * 10221293   \
    + __TIME__[0x3] * 10716197   \
    + __TIME__[0x4] * 10913537   \
    + __TIME__[0x6] * 14346811   \
    + __TIME__[0x7] * 15485863
    
    unsigned HASH_STATE = HASH_SEED;
    unsigned HASH() {
        return HASH_STATE = HASH_STATE * HASH_A % HASH_B;
    }
    

    Using the hash function:

    template 
    class A
    {
    public:
        static const unsigned int ID;
    };
    
    template <>
    const unsigned int A::ID = HASH();
    
    template <>
    const unsigned int A::ID = HASH();
    
    template <>
    const unsigned int A::ID = HASH();
    
    template <>
    const unsigned int A::ID = HASH();
    
    #include 
    
    int main() {
        std::cout << A::ID << std::endl;
        std::cout << A::ID << std::endl;
        std::cout << A::ID << std::endl;
        std::cout << A::ID << std::endl;
    }
    

提交回复
热议问题