带有类 - 非静态成员调用的 typedef 函数声明

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

本文关键字:typedef 函数 声明 调用 静态成员      更新时间:2023-10-16

我有以下类,称为HashMap,一个构造函数可以接受用户提供的HashFunction - 然后是我实现的那个。

面临的问题是在没有提供的情况下定义我自己的HashFunction。以下是我正在使用的示例代码并从 gcc 收到错误:

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

头文件:

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;
}

源文件:

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是一个

成员函数,它与普通函数有很大不同。成员函数具有隐式this指针,并且始终需要在对象上调用。为了将其分配给std::function,您可以使用std::bind来绑定当前实例:

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

但是,您应该看到标准库如何使用 std::hash 做到这一点。