I am trying to create a std::unordered_map
where the value is a std::type_index
. The following snippet works:
std::unordered_map<std::type_index, int> workingMap;
workingMap[typeid(int)] = 1;
workingMap[typeid(char)] = 2;
But this one doesn't run and throws an error:
std::unordered_map<int, std::type_index> failingMap;
failingMap[1] = typeid(int);
failingMap[2] = typeid(char);
CS2512: 'std::type_index::type_index': no appropriate default constructor available.
I don't fully understand this error, what is the difference between the constructors in these examples? Is it possible to make a map where typeid(..)
is the value instead of the key?
The issue is
operator[]
, not the actual use of the map. The problem is if the key is not found,operator[]
will assign a default value and return a modifiable reference to that value, which is impossible withstd::type_index
. You may useemplace
,insert
,try_emplace
, or any other modifier that does not require a default constructor.