我看过几篇关于 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/