我正在尝试编写一个函数,当键不在std::map内时,它会给我一个默认值。在任何情况下,我的默认值都是numerical_limit::infinity((。悬停这个简单的例子不起作用。
#include <iostream>
#include <map>
#include <limits>
template<typename KeyType, typename ValueType>
ValueType mapDefaultInf(const std::map<KeyType, ValueType> & map, const KeyType & key)
{
if(!map.contains(key))
{
return std::numeric_limits<ValueType>::infinity();
}
else
{
return map[key];
}
}
int main()
{
std::map<std::string, int> map;
auto el = mapDefaultInf(map, "alexey");
std::cout << el << std::endl;
return 0;
}
错误为:
main.cpp:29:42: error: no matching function for call to ‘mapDefaultInf(std::map, int>&, const char [7])’
有人能帮我理解这个错误吗。
提前谢谢。
您对模板的约束过多,因为它要求映射中的键与key
参数的类型相同。
这失败了,因为您的映射存储std::string
,但您传递了一个字符串文字,从技术上讲,它的类型为const char[7]
。
只需制作标题:
template<typename KeyType, typename ValueType,typename T>
ValueType mapDefaultInf(const std::map<KeyType, ValueType> & map, const T& key)
它将允许在map.contains(key)
调用中进行隐式转换,如果您向它传递不兼容的类型,它只会失败并显示更复杂的错误消息。无论如何,当前的错误并不是可读性的巅峰。
首先在函数内的映射对象上使用operator[]
。这是不允许的,因为它是一个非常量函数,并且您通过const引用传递了映射。相反,您应该重写函数实现以使用迭代器:
template<typename KeyType, typename ValueType>
ValueType mapDefaultInf(const std::map<KeyType, ValueType> & map, const KeyType & key)
{
const auto it = map.find(key);
return it != map.end() ? it->second : std::numeric_limits<ValueType>::infinity();
}
其次,您在键类型中存在歧义。您需要传入一个std::字符串。像这样:
auto el = mapDefaultInf(map, std::string("alexey"));