0

I want to have a pair as a key for an unordered_map which by default doesn't provide such a hash hence I am replicating the boost hash APIs but running into some issues.

This is how I instantiated a map using a pair

using pair = std::pair<Values, std::string>;
std::unordered_map<pair, int, custom_hash<pair>> mp;

And this is how it's being used

void Foo(Values firstKey, std::string secKey, int value)
{
    mp.insert({{firstKey, secKey}, value});
}

with Values being an enum, I get an error saying:

could not convert 'val' from 'Values' to 'std::__hash_enum<Values, true>'.

Does that mean T can't be of enum type? Sample code

template <class T>
std::size_t hash_value(T val)
{
    return std::hash<T>(val);
}

template <class T>
inline void hash_combine( std::size_t& seed, T const& v)
{
    custom_hash<T>()(v);
}

template <class A, class B>
std::size_t hash_value(std::pair<A, B> const& v)
{
  std::size_t seed = 0;

  hash_combine(seed, v.first);
  hash_combine(seed, v.second);

  return seed;
}

template <class T> struct custom_hash
{
    typedef T argument_type;
    typedef std::size_t result_type;

    std::size_t operator()(T const& val) const
    {
        return hash_value(val);
    }
};

enum class Values
{
    one
};

using pair = std::pair<Values, std::string>;
std::unordered_map<pair, int, custom_hash<pair>> mp;

void Foo(Values firstKey, std::string secKey, int value)
{
    mp.insert({{firstKey, secKey}, value});
}
xyf
  • 664
  • 1
  • 6
  • 16

0 Answers0