std::remove_const<std::unordered map> doesn't seem to be working

Viewed 59
void foo( const std::unordered_map<char, int> & m )
{
    using M = std::remove_const< decltype( m ) >;
    M mutable_map;
    mutable_map['a'] = 42;
}

This fails with "no match for operator[]". In my actual code I carry the map inside an std::pair and there the error message is clearer: "passing const std::unordered_map<...> as this discards qualifiers".

What's wrong? I can't use const_cast<>() because I don't know the type (the map template parameters).

1 Answers

First problem is that you are using std::remove_const instead of: std::remove_const::type or std::remove_const_t.

Second problem is that you need a value, not a reference, so you need discard also a reference, so you need std::decay_t.

Demo

#include <unordered_map>
#include <type_traits>

void foo( const std::unordered_map<char, int> & m )
{
    using M = std::decay_t< decltype( m ) >;
    M mutable_map;
    mutable_map['a'] = 42;
}
Related