Compile-time constant id

前端 未结 16 2143
不知归路
不知归路 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:33

    What I usually use is this:

    template
    void type_id(){}
    
    using type_id_t = void(*)();
    

    Since every instantiation of the function has it's own address, you can use that address to identify types:

    // Work at compile time
    constexpr type_id_t int_id = type_id;
    
    // Work at runtime too
    std::map types;
    
    types[type_id] = 4;
    types[type_id] = "values"s
    
    // Find values
    auto it = types.find(type_id);
    
    if (it != types.end()) {
        // Found it!
    }
    

提交回复
热议问题