如何为集合提供带迭代器的const接口? [英] How to provide const interface with iterators to a collection?
问题描述
我想用这样的签名创建一个函数:
I would like to create a function with a signature like this:
// Set found to be an iterator to the location of key in map or end()
// if not found.
bool lookup(const Key &key,
const std::map<Key, Value> &map,
std::map<Key, Value>::const_iterator &found);
但是我想在地图和迭代器不是const的情况下调用它以便我可以修改找到的值:
But I would like to also call it in cases where the map and iterator are not const so that I can modify the found value:
const Key key;
std::map<Key, Value> map;
std::map<Key, Value>::iterator found;
if (lookup(key, map, found)) {
found->second.modifingNonConstFunction()
}
但我不相信我可以传递 std :: map< Key,Value> :: iterator
对象期望引用 std :: map< Key,Value> :: const_iterator
,因为它们是不同的类型,而我通常可以在 const
是类似C ++声明的一部分,我可以将非const类型提升为const类型:
But I do not believe I can pass a std::map<Key, Value>::iterator
object to a function expecting a reference to a std::map<Key, Value>::const_iterator
since they are different types, whereas I normally could if the const
was part of C++ declaration of the type like this and I could promote the non-const type to a const type:
void someFunction(const int &arg);
int notConstArg = 0;
someFunction(nonConstArg);
除了使用模板为 lookup()提供两个定义
,一个如 const
参数2和3以及另一个非const参数2和3所示,在C ++中有更好的方法来实现这一点类似于 const int&
如何在上面的例子中传递一个非const int
。换句话说,我可以只有一个功能而不是两个吗?
Other than by using templates to provide two definitions for lookup()
, one as shown with const
arguments 2 and 3 and another with non-const arguments 2 and 3, is there a better way in C++ to accomplish this more akin to how const int &
can be passed a non-const int
in the example above. In other words, can I just have a single function and not two?
推荐答案
不,我认为你不能做这没有重载/模板魔术。
No, I don't think you can do this without overloads/template magic.
编译器正在保护您免受以下情况的影响:
The compiler is protecting you from the following scenario:
typedef vector<int> T;
const T v; // Can't touch me
void foo(T::const_iterator &it) {
it = v.begin(); // v.begin() really is a const_iterator
}
int main() {
T::iterator it;
foo(it);
*it = 5; // Uh-oh, you touched me!
}
这篇关于如何为集合提供带迭代器的const接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!