2013-11-15 74 views
0

我有以下類,稱爲HashMap,其中一個構造函數可以接受用戶提供的HashFunction - 然後是我實現的一個。帶類的typedef函數聲明 - 非靜態成員調用?

我面臨的問題是在沒有提供任何東西時定義我自己的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

'hashCompressFunction'是一個成員函數,它具有與獨立函數不同的簽名。 – billz

+0

有一個原因,大多數散列實現需要一個函數而不是 –

+0

@billz好吧,這是有道理的。通過在類之外刪除我的'HashCompressFunction',我可以編譯。然而,現在問題出現在'HashCompressFunction'不再可以訪問成員函數或'HashClass'中的變量 - IE桶大小。是製作靜態類的唯一解決方案嗎? – Adam

回答

1

hashCompressFunction是一個成員函數,與正常功能非常不同。成員函數有一個隱含的指針,總是需要在一個對象上調用。 爲了將其分配給std::function,你可以使用std::bind當前實例綁定:

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

但是,你應該看到標準庫是怎麼做的,有std::hash