Compile-time constant id

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

    Another alternative is to consider the following class Data with the unique, static member field type:

    template 
    class Data
    {
    public:
        static const std::type_index type;
    };
    // do [static data member initialization](http://stackoverflow.com/q/11300652/3041008)
    // by [generating unique type id](http://stackoverflow.com/q/26794944/3041008)
    template 
    std::type_index const Data::type = std::type_index(typeid(T));
    

    produces the output (MinGWx64-gcc4.8.4 -std=c++11 -O2)

    printf("%s %s\n", Data::type.name(), Data::type.name())
    //prints "i f"
    

    It's not exactly an integer id or pretty-printable string, nor a constexpr, but can be used as an index in (un)ordered associative containers.
    It also appears to work if the Data.h header is included in multiple files (same hashCode() values).

提交回复
热议问题