我有一個哈希表類。它有一個模板引數hashFunction:
#include <string>
template<class KeyType> using hashFunction_t = size_t(size_t, const KeyType&);
template< class KeyType, class ValueType, int nHashGroups,
hashFunction_t<KeyType> hashFunction >
class HashTable
{
};
class Entity
{
//djb2
size_t stringHash(size_t nGroups, const std::string& key)
{
unsigned long hash = 5381;
const char* str = key.c_str();
int c = 0;
while (c = *str )
hash = ((hash << 5) hash) c;
return hash % nGroups;
}
HashTable <std::string, int, 10, stringHash> ht;
};
int main()
{
Entity{};
}
我更愿意stringHash將Entity類中的函式作為私有函式隱藏,但這樣做會給我一個錯誤:
Error (active) E0458 argument of type
"size_t (Entity::*)(size_t nGroups, const std::string &key)"
is incompatible with template parameter of type
"hashFunction_t<std::string> *"
我怎樣才能做到這一點?
uj5u.com熱心網友回復:
問題是您試圖使用指向成員的指標作為型別模板引數,這不受支持,主要是因為當您定義型別時,您不會將該型別系結到任何特定物件。
當(如評論中所建議的)您制作stringHash靜態時,您不再需要該物件,因此可以使用它來定義型別。
如果您仍然需要stringHash來自非靜態成員,那么您可以將模板更改為如下所示。請注意,您必須將物件傳遞給HashTable才能呼叫hashFunction. 另外,請注意呼叫它的語法。
template<class KeyType, class Obj> using hashFunction_t =
size_t(Obj::*)(size_t, const KeyType&);
template< class KeyType, class ValueType, int nHashGroups,
class Obj, hashFunction_t<KeyType, Obj> hashFunction>
class HashTable
{
public:
explicit HashTable(Obj& obj) : m_obj{obj} {
(m_obj.*hashFunction)(10, ""); // arguments just for illustrative purposes
}
private:
Obj& m_obj; // keep a reference to the object to call the method
// be careful with dangling references
};
class Entity
{
size_t stringHash(size_t nGroups, const std::string& key)
/* ... */
// Pass a reference to the object
HashTable <std::string, int, 10, Entity, &Entity::stringHash> ht{*this};
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/419331.html
標籤:
