Search code examples
c++algorithmhashfunctorunordered-map

Why for_each requires an instance to be passed as an argument while the hash unary function for unordered map does not in C++?


To construct an unordered map with a customized hash function

struct EnumClassHash
{
    template <typename T>
    std::size_t operator()(T t) const
    {
    return static_cast<std::size_t>(t);
    }
};

enum class MyEnum {};

std::unordered_map<MyEnum, int, EnumClassHash> myMap;

To construct a for_each function

struct Class
{ 
    void operator() (int a) 
    { 
        cout << a * 3 << " "; 
    } 
};

for_each(arr, arr + 5, Class()); 

// or equivalently
Class ob;
for_each(arr, arr + 5, ob); 

why does for_each require an instance to be passed while an unordered map's hasher can take a class directly (EnumClassHash vs Class() / ob)?


Solution

  • When you write

    std::unordered_map<MyEnum, int, EnumClassHash>
    

    you are specifying a type. When you write

    for_each(arr, arr + 5, Class());
    

    you are specifying an expression. These are two very different things.