无法从地图获取key_type

unable to get key_type from a map

本文关键字:key type 获取 地图      更新时间:2023-10-16

我写这段代码是为了检查std::map是否包含特定的键:

template<typename T, typename... Args >
inline bool contains(const std::map<Args...>& map, const T& value) noexcept
{
static_assert(std::is_constructible_v< decltype(map)::key_type , T >);
return map.find(value) != std::end(map);
}

我有以下错误:

错误:key_type不是const std::map<std::__cxx11::basic_string<char>, Query>&的成员

decltype(map)::key_type有什么问题?

错误非常明确,decltype(map)const std::map<Args... >&,这是对std::mapconst引用。由于它是引用类型,因此它没有::key_type

您需要使用std::remove_reference_t删除引用:

static_assert(std::is_constructible_v<
typename std::remove_reference_t<decltype(map)>::key_type,
T 
>);

您需要typename,因为std::remove_reference_t<decltype(map)>是依赖名称。

一种更惯用的方法是使用Map模板参数,而不是将函数限制为std::map

template<typename T, typename Map>
inline bool contains(const Map &map, const T& value) noexcept {
static_assert(std::is_constructible_v< typename Map::key_type , T >);
return map.find(value) != std::end(map);
}