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);
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()
}
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);
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: