简体   繁体   中英

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)?

std::unordered_map does actually have an overloaded constructor that takes an instance of the comparator as a parameter, if you wish to provide one. Otherwise std::unordered_map default-constructs the comparator. It can do that because it knows what the comparator class is, it's given right there, in the template.

On the other hand, where do you think std::for_each could possibly get the UnaryFunction class instance , if it's not passed explicitly as its third parameter? Let's say you have this example:

std::for_each(container.begin(), container.end());

How would this std::for_each know what'll gobble up the sequence? I suppose that the container's class could be made an explicit template parameter for std::for_each , but that unnecessarily complicates the interface and doesn't really add much value.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM