Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unable to get key_type from a map

Tags:

c++

c++11

I wrote this piece of code in order to check if a std::map contains a specific key:

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);
}

I have the following error:

error: key_type is not a member of const std::map<std::__cxx11::basic_string<char>, Query>&

What is the problem with decltype(map)::key_type?

like image 735
Kafka Avatar asked Dec 20 '19 10:12

Kafka


1 Answers

The error is quite explicit, decltype(map) is const std::map<Args... >&, which is a const-reference to a std::map. Since it's a reference type, it does not have a ::key_type.

You need to use std::remove_reference_t to drop the reference:

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

You need the typename because std::remove_reference_t<decltype(map)> is a dependent name.

A more idiomatic way would be to use a Map template parameter and not constrain the function to 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);
}
like image 128
Holt Avatar answered Oct 11 '22 08:10

Holt