c++ - 在模板运算符 [] 中删除 "const int"限定符

标签 c++ stl

我看过几篇关于 const 限定符的帖子,但我无法弄清楚如何解决这个问题。我正在构建一个以 STL map 类为模型的类,并且我使用 STL 集类作为基类:

template <class Key, class Value>
class map : public std::set <std::pair<Key, Value> > {
public:
    typedef std::set<std::pair<Key, Value> > parent;
    typedef typename std::set<std::pair<Key, Value> >::iterator iterator;

    // constructors
    map() : parent() {}
    map(map<Key, Value>& m) : parent(m) {}

    // definition for subscript operator
    Value& operator [] (const Key &);

    // overloaded methods from set
    void erase(Key&);
    void erase(iterator& itr) {
        parent::erase(itr);
    }

    int count(Key&);
    iterator find(Key&);
    iterator lower_bound(Key& k) {
        return parent::lower_bound(k);
    }

    iterator upper_bound(Key& k) {
        return parent::upper_bound(k);
    }

    // not found iterator
    iterator end() {
        return parent::end();
    }

};

问题出在 operator[] 重载函数上,它看起来像:

template <class Key, class Value>
Value&  map<Key, Value>::operator[] (const Key& k) {
    std::pair<Key, Value> test;
    test.first = k;

    std::pair<iterator, bool> where = parent::insert(test);

    return (*(where.first)).second;
}

编译器给我错误“...map.h:108:16:将对‘int’类型的引用绑定(bind)到‘const int’类型的值会丢弃限定符”。我意识到它看到 (*(where.first)).second 被评估为“const int”,我将其返回到“int”,因为我已将 map 声明为:

map<std::string, int> mymap;
mymap["one"] = 1;

看来 std::pair<...>被定义为 std::pair<std::string, const int>而不是 std::pair<std::string, int> .至少这是我的推测。我一定是遗漏了一些简单的东西,但我没有看到它。非常感谢任何帮助。

最佳答案

问题是 std::set 元素是不可变的(否则你可以任意修改它们并在 set 不知情的情况下弄乱顺序);这是通过其返回 const 迭代器的方法强制执行的。

因此,*(where.first)const,因此 (*(where.first)).second 也是。所以你不能返回一个非 const 引用给它。

关于c++ - 在模板运算符 [] 中删除 "const int"限定符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15866296/

相关文章:

c++ - 链接器错误LNK2019和LNK1120

c++ - 将局部变量存储在类的 STL 容器中安全吗?

c++ - 对于 std::vector,如何在没有 .resize() 的情况下使用有效的 .begin() 和 .end()?

c++ - vector 问题 (std::out_of_range)

C++ 如何打印复合 vector 的内容

c++ - 方法参数的内存错误(访问冲突)

c++ - 使用克隆(): segmentation fault

c++ - 奇怪的 C++ std::string 行为......我该如何解决这个问题?

c++ - 如何更改STL列表中项目的值?

c++ - 段错误 11 在不同机器上的行为