【问题标题】:std::remove_const<std::unordered map> doesn't seem to be workingstd::remove_const<std::unordered map> 似乎不起作用
【发布时间】:2021-09-25 19:12:01
【问题描述】:
void foo( const std::unordered_map<char, int> & m )
{
    using M = std::remove_const< decltype( m ) >;
    M mutable_map;
    mutable_map['a'] = 42;
}

这会失败并显示“与 operator[] 不匹配”。在我的实际代码中,我将地图放在std::pair 中,并且错误消息更清晰:“将const std::unordered_map&lt;...&gt; 传递为this 丢弃限定符”。

怎么了?我不能使用const_cast&lt;&gt;(),因为我不知道类型(地图模板参数)。

【问题讨论】:

    标签: constants c++20 unordered-map


    【解决方案1】:

    第一个问题是您使用的是std::remove_const 而不是: std::remove_const::typestd::remove_const_t

    第二个问题是你需要一个值,而不是一个引用,所以你还需要丢弃一个引用,所以你需要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;
    }
    

    【讨论】:

      猜你喜欢
      • 2014-05-27
      • 2017-11-11
      • 1970-01-01
      • 2018-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-27
      • 2020-09-08
      相关资源
      最近更新 更多