0

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
2
  • About the << 1 thing: If you need it depends on your requirements. The code is correct in both cases (well, that part) Commented Oct 21, 2015 at 0:42
  • @deviantfan Thanks, I figured since I wasn't combining it. Commented Oct 21, 2015 at 0:53

1 Answer 1

3
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;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, looks like those errors are gone now. However, the compiler is still complaining "The C++ standard doesn't provide a hash for this type." I don't see how that's possible given I'm specifying the third parameter. Does my operator() overload look okay? Just trying to think what else it could be. EDIT: Nevermind, forgot to make the same changes to a different class elsewhere.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.