簡體   English   中英

類的typedef函數聲明-非靜態成員調用?

[英]typedef function declaration with class - non-static member call?

我有一個名為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看到標准庫是如何做到的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM