I am creating a Template Cache library in C++-11 where I want to hash the keys. I want to use default std::hash for primitive/pre-defined types like int, std::string, etc. and user-defined hash functions for user-defined types. My code currently looks like this:
template<typename Key, typename Value>
class Cache
{
typedef std::function<size_t(const Key &)> HASHFUNCTION;
private:
std::list< Node<Key, Value>* > m_keys;
std::unordered_map<size_t, typename std::list< Node<Key, Value>* >::iterator> m_cache;
size_t m_Capacity;
HASHFUNCTION t_hash;
size_t getHash(const Key& key) {
if(t_hash == nullptr) {
return std::hash<Key>(key); //Error line
}
else
return t_hash(key);
}
public:
Cache(size_t size) : m_Capacity(size) {
t_hash = nullptr;
}
Cache(size_t size, HASHFUNCTION hash) : m_Capacity(size), t_hash(hash) {} void insert(const Key& key, const Value& value) {
size_t hash = getHash(key);
...
}
bool get(const Key& key, Value& val) {
size_t hash = getHash(key);
...
}
};
My main function looks like this:
int main() {
Cache<int, int> cache(3);
cache.insert(1, 0);
cache.insert(2, 0);
int res;
cache.get(2, &res);
}
On compiling the code above, I get the below error:
error: no matching function for call to ‘std::hash<int>::hash(const int&)’
return std::hash<Key>(key);
Can anyone please help me out here and point out what am I missing or doing it incorrectly?
In this call you provide the constructor of
std::hash<Key>withkey:You want to use it's member function,
size_t operator()(const Key&) const;:Some notes: Hashing and caching are used to provide fast lookup and having a
std::functionobject for this may slow it down a bit. It comes with some overhead:The same goes for the check in
getHash()that is done every time you use it:It would probably be better to add a template parameter for what type of hasher that is needed. For types with
std::hashspecializations, that could be the default. Otherwisesize_t(*)(const Key&)could be the default. A user could still override the default and demand that the hash function is astd::function<size_t(const Key &)>if that's really wanted.If a hash function is to be used, I recommend requiring the user to supply it when a
Cacheis constructed. That way you can skip theif(t_hash == nullptr)check every time the hash function is used.First a small type trait to check if
std::hash<Key>exists:The added template parameter in
Cachecould then be conditionally defaulted to eitherstd::hash<Key>orsize_t(*)(const Key&)and you could disallow constructing aCachewith only a size when a pointer to a hash function is needed:The usage would be the same as before, except you can't construct a
Cachewithout a hasher: