I have several std::map<some_type, some_other_type>
and I'm trying to write a function template Lookup
as shown below.
The function template works fine when the key is a pointer or a scalar, but if the key is std::string
there are problems.
#include <iostream>
#include <map>
// Usage :
// bool valueisinmap = Lookup(themap, thekey, thevalue);
template <typename TK, typename TV>
bool Lookup(std::map<TK, TV>& map, TK key, TV& value)
{
auto it = map.find(key);
if (it != map.end())
{
value = it->second;
return true;
}
else
{
return false;
}
}
int main()
{
std::map<std::string, std::string> m;
m.insert(std::make_pair("2", "two"));
std::string x;
std::string key = "2";
if (Lookup(m, key, x))
std::cout << "OK\n";
if (Lookup(m, "2", x)) // problem here
std::cout << "OK\n";
}
I understand why Lookup(m, "2", x)
doesn't compile because the type of "2"
is not std::string
but is there a way to write the function template so I can use Lookup(m, "2", x)
as well as Lookup(m, key, x)
, key
being a std::string
?
And if yes this raises a second question:
bool Lookup(std::map<TK, TV>& map, TK key, TV& value)
key
is passed by value and if the type of key
is std::string
, a copy is made. Is there a way to pass key
by reference (or some C++14 and plus magic) and still being able to use Lookup(m, "2", x)
?