我有几个std::map<some_type, some_other_type>
我正在尝试编写一个函数模板 Lookup
如下所示。
当键是指针或标量时,函数模板可以正常工作,但如果键是 std::string
有问题。
#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";
}
我明白为什么Lookup(m, "2", x)
无法编译,因为 "2"
的类型不是std::string
但有没有办法编写函数模板,以便我可以使用 Lookup(m, "2", x)
以及 Lookup(m, key, x)
, key
是 std::string
?
如果是的话,这就提出了第二个问题:
bool Lookup(std::map<TK, TV>& map, TK key, TV& value)
key
按值传递,如果 key
的类型是 std::string
,复制一份。有没有办法通过key
通过引用(或一些 C++14 和 plus magic)并且仍然能够使用 Lookup(m, "2", x)
?
最佳答案
解决这个问题的一种方法是为键类型引入一个单独的类型参数,如下所示:
template <typename TKM, typename TK, typename TV>
bool Lookup(const std::map<TKM, TV>& map, const TK& key, TV& value)
{
auto it = map.find(key);
if (it != map.end())
{
value = it->second;
return true;
}
else
{
return false;
}
}
只要 TK
可以隐式转换为 TKM
,就可以使用 TK
类型的键调用 Lookup
> 与具有键类型 TKM
的 map 结合使用。
关于c++ - 函数模板和模棱两可的模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58182792/