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

标签 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;
    ...
}

最佳答案

hashCompressFunction 是一个成员函数,与普通函数有很大的不同。成员函数有一个隐式的 this 指针,并且总是需要在对象上调用。 为了将其分配给 std::function,您可以使用 std::bind 绑定(bind)当前实例:

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

然而,你应该看看标准库是如何做到的,用 std::hash .

关于c++ - 带有类的 typedef 函数声明 - 非静态成员调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19992788/

相关文章:

c - 如何在 C 中创建对象数组?

c++ - ifstream 找不到文件?

c++ - 垃圾收集事件的 LuaPlus 和 c++ 回调

c++ - 我类的意外加法运算符

c++ - 数组作为映射键

c++ - 检查转换对象的原始类型

使用 typename 并将 typedef 传递给函数的 C++ 模板

c - C中的typedef结构问题

c++ - for循环在cpp中只执行一次

c++ - 如何在C++中将此函数重写为指针?