我想创建一个具有如下签名的函数:
// 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 的情况下调用它,以便我可以修改找到的值:
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 类型:
void someFunction(const int &arg);
int notConstArg = 0;
someFunction(nonConstArg);
除了使用模板提供两个定义之外lookup()
,如图所示const
参数 2 和 3 以及另一个具有非常量参数 2 和 3 的参数,C++ 中是否有更好的方法来完成此任务,更类似于如何const int &
可以传递一个非常量int
在上面的例子中。换句话说,我可以只拥有一个功能而不是两个吗?