c++ - 函数模板和模棱两可的模板参数

标签 c++ templates stdmap

我有几个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) , keystd::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/

相关文章:

c++ - 不使用内置函数(如 atoi 或 atof)将字符串转换为 float 或整数

javascript - 使用 jquery/d3 动态重用模板

c++ - std::map::iterator 递减单个元素

c++ - 我的自制小应用程序立即关闭

C++如何将字符串数组中的点设置为枚举变量

c++ - DirectX 11 获取显卡的描述

三重嵌套模板参数的 C++ 正确语法

vba - 使用 VBA 在 Word 模板中填充表格?

c++ - std::map::begin() 返回一个带垃圾的迭代器

c++ - 如何在 C++ 中导出具有返回类型 std::map 的函数