mdeforge
mdeforge

Reputation: 874

What's wrong with my hash key type and function?

I'm trying to write my own hash function for a class that is essentially a wrapper for an unsigned integer. I've been trying to follow this thread here: and this resource here. Why doesn't this work? See code comment for errors.

struct Entity
{
    unsigned int id;

    bool operator==( const Entity &other ) const
    {
        return ( id == other.id );
    }
};

template<struct T>
class EntityHash;

template<>
class EntityHash<Entity> // Error: Type name is not allowed
{
public:
    std::size_t operator()( const Entity& entity ) const
    {
        size_t h1 = std::hash<unsigned int>()( entity.id );
        return h1; // Also... do I need a << 1 at the end of this to bitshift even though I'm not combining?
    }
};

// Elsewhere
std::unordered_map<Entity, unsigned int, EntityHash> map; // Error: Argument list for class template EntityHash is missing

Upvotes: 0

Views: 238

Answers (1)

aschepler
aschepler

Reputation: 72431

template <struct T>
class EntityHash;

is probably not what you want. Use template <class T> or template <typename T>.

The third template argument of unordered_map must be a type, not the name of a template. So:

std::unordered_map<Entity, unsigned int, EntityHash<Entity>> map;

Upvotes: 3

Related Questions