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

时间:2013-11-15 03:06:43

标签: c++ c++11 typedef

我有以下类,称为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;
    ...
}

1 个答案:

答案 0 :(得分:1)

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

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

但是,您应该看到标准库如何使用std::hash