简体   繁体   中英

typedef function declaration with class - non-static member call?

I have the following class, called HashMap, which one constructor can accept a user supplied HashFunction -- then the one I implement.

The problem I am facing is defining my own HashFunction when none is provided. The following is sample code I am working with and getting the error from gcc:

HashMap.cpp:20:20: error: reference to non-static member function must be called
    hashCompress = hashCompressFunction;
                   ^~~~~~~~~~~~~~~~~~~~`

Header File:

class HashMap
{
    public:
        typedef std::function<unsigned int(const std::string&)> HashFunction;
        HashMap();
        HashMap(HashFunction hashFunction);
        ...
    private:
        unsigned int hashCompressFunction(const std::string& s);
        HashFunction hashCompress;
}

Source File:

unsigned int HashMap::hashCompressFunction(const std::string& s) 
{
    ... my ultra cool hash ...

    return some_unsigned_int;
}

HashMap::HashMap()
{
    ...
    hashCompress = hashCompressFunction;
    ...
}

HashMap::HashMap(HashFunction hf)
{
    ...
    hashCompress = hf;
    ...
}

hashCompressFunction is a member function, which is very different from a normal function. A member function has an implicit this pointer and always needs to be called on an object. In order to assign it to std::function , you could use std::bind to bind the current instance:

hashCompress = std::bind(&HashMap::hashCompressFunction, 
                         this, std::placeholders::_1);

However, you should see how the standard library does it, with std::hash .

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