Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert templated type into ID

I have a project where I need to have the ability to convert a given type into an ID.

This code doesn’t compile, but I hope it shows the functionality I am trying to achieve.

class TypeIDManager {
public:
    template <typename Type>
    void setTypeID(std::size_t ID) {
        m_data.insert({ typeid(Type), ID });
    }

    template <typename Type>
    std::size_t getTypeID() {
        return m_data[typeid(Type)];
    }

private:
    std::unordered_map<std::type_info, std::size_t> m_data;
};

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

That’s what std::type_index is meant for:

std::unordered_map<std::type_index, std::size_t> m_data;

std::type_info is implicitly convertible to std::type_index via its converting constructor, so you don’t need to change the way you insert into the map.

However std::type_index doesn’t have a default constructor which is required for std::unordered_map‘s operator[].

So you will need to use the find/at methods instead to retrieve values, e.g.

return m_data.at(typeid(Type));

which will throw an exception if the key isn’t found.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading