我写了这段代码是为了检查 a 是否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);
}
Run Code Online (Sandbox Code Playgroud)
我有以下错误:
错误:
key_type不是成员const std::map<std::__cxx11::basic_string<char>, Query>&
有什么问题decltype(map)::key_type?
Hol*_*olt 10
错误非常明确,decltype(map)is const std::map<Args... >&,它是对 a 的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
>);
Run Code Online (Sandbox Code Playgroud)
您需要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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
243 次 |
| 最近记录: |