fortytoo
fortytoo

Reputation: 462

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;
};

Upvotes: 0

Views: 182

Answers (1)

user17732522
user17732522

Reputation: 76709

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.

Upvotes: 3

Related Questions