删除模板运算符中的"const int"限定符[]
Dropping "const int" qualifiers in template operator[]
我看过几篇关于const限定符的文章,但我不知道如何解决这个问题。我正在构建一个以STL映射类为模型的类,并且我使用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'到类型'const int'的值会降低限定符"。我意识到它正在看到(*(where.first))。第二个被求值为"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
的引用。
相关文章:
- 'max'匹配'std::function<const int &(const int &, const int &)>'无过载
- 在C++中,如果"int a = 3; int* p = &a;",那么为什么不允许"const int* &pp = p",但允许"const int* const &pp = p"?
- 调用'myStud::myStud(int, const char [5], int, int, int)'没有匹配函数
- 返回对象时从'const DList<int>* const'到 'DList<int>*' [-fallowive] 的转换无效
- int(int)& 或 int(int) const &是什么类型?
- 传递 const int* 和 int* 时调用重载函数的不同版本(const int* const&/&&)
- 如何在构造函数中初始化int const * const
- 对"displayForStudent(int, int const*, double const*, int)"的未定义引用 collect2.exe:错误:ld 返回 1 个退出状态
- 如何在 C++ 中解释"const int *const & variable"
- 为什么"int & const" MSVC 编译得很好?
- const int const&和const int&in C++有什么区别?
- std::set<int * const> 不会编译
- " invalid operands of types 'int' and 'int* const'" 来自功能的错误,来自书
- std::initializer_list<int const> 不能从 std::initializer_list <int>构造
- 对'std::string Helper::ToString<int>(int const&)'的未定义引用
- 无法弄清楚 int[3][3] 和 int(* const)[3] 之间的区别
- const int* const fun(const int* const& p) const的含义;
- 为什么vector<int * const>是非法/不合逻辑的?
- 对 Stack<int>::p ush(int const&) 的未定义引用
- JsonCpp:未定义的对"Json::Value::operator[](int) const"的引用