我编写这段代码是为了检查 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);
}
我有以下错误:
error:
key_type
is not a member ofconst std::map<std::__cxx11::basic_string<char>, Query>&
decltype(map)::key_type
有什么问题吗? ?
最佳答案
错误非常明显,decltype(map)
是 const std::map<Args... >&
,这是 const
-引用std::map
。由于它是引用类型,因此它没有 ::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);
}
关于c++ - 无法从 map 获取 key_type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59423984/