Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hash std::string_view?

I am trying to define my own hashing function for std::unordered_map and I want to hash a field within a struct which is supposed to be the key. The code below is a simplified version of what I have:

struct TestStruct {
    char a[64];
    char b[64];
}

struct my_eq {
    bool operator()(const TestStruct& test_1, const TestStruct& test_2) const {
        return !strcmp(test_1.a, test_2.a) && !strcmp(test_1.b, test_2.b);
    }
};

struct my_hash {
    unsigned long operator()(const TestStruct& test) const {
        return std::hash<std::string_view>(std::string_view(test.a));
    }
};
std::unordered_map<TestStruct, int, my_hash,my_eq> map;

The error I get is:

no matching function for call to ‘std::hash<std::basic_string_view<char> >::hash(std::string_view&)

According to the cppreference on std::hash the hash function should support std::string_view. I feel like I'm missing something simple but I cannot figure it out.

like image 1000
ajoseps Avatar asked Jun 05 '26 21:06

ajoseps


1 Answers

std::hash is a class template, not a function template. you need an instance to call it:

return std::hash<std::string_view>()(std::string_view(test.a));
like image 76
llllllllll Avatar answered Jun 07 '26 12:06

llllllllll