c++ - 无法从 map 获取 key_type

标签 c++ c++11

我编写这段代码是为了检查 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 of const 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/

相关文章:

c++ - 从成员变量访问静态 constexpr 成员,GCC 错误?

c++ - 在 Windows 上包含 sys/times.h 的替代方法是什么?

c++ - 如何在 Cmake 中定义传递 CXX_STANDARD C++11

c++ - 运算符 '=' 不匹配(std::array<T, 3> 和 std::initializer_list<T>)

linux - VS2017 在 Linux Remote 上调试我的共享库

c++ - 在 OpenGL 中构建网格

c++ - 关于函数引用和线程的问题

c++ - std::all_of 不接受类成员函数作为具有 1 个参数的函数

c++ - 我的代码是未定义的行为吗

c++11 decltype 返回引用类型