2015-10-21 38 views
0

我想爲我自己的散列函數編寫一個基本上是無符號整數封裝的類。我一直試圖按照這個線程here:和這個資源here。爲什麼這不起作用?查看代碼註釋以瞭解錯誤。我的散列鍵類型和函數有什麼問題?

struct Entity 
{ 
    unsigned int id; 

    bool operator==(const Entity &other) const 
    { 
     return (id == other.id); 
    } 
}; 

template<struct T> 
class EntityHash; 

template<> 
class EntityHash<Entity> // Error: Type name is not allowed 
{ 
public: 
    std::size_t operator()(const Entity& entity) const 
    { 
     size_t h1 = std::hash<unsigned int>()(entity.id); 
     return h1; // Also... do I need a << 1 at the end of this to bitshift even though I'm not combining? 
    } 
}; 

// Elsewhere 
std::unordered_map<Entity, unsigned int, EntityHash> map; // Error: Argument list for class template EntityHash is missing 
+0

關於'<< 1'的事情:如果你需要它取決於你的要求。代碼在這兩種情況下都是正確的(當然,那部分) – deviantfan

+0

@deviantfan謝謝,我想,因爲我沒有合併它。 – Stradigos

回答

3
template <struct T> 
class EntityHash; 

可能不是你想要的。使用template <class T>template <typename T>

unordered_map的第三個模板參數必須是一個類型,而不是模板的名稱。所以:

std::unordered_map<Entity, unsigned int, EntityHash<Entity>> map; 
+0

謝謝,看起來那些錯誤現在已經消失了。但是,編譯器仍在抱怨:「C++標準不提供這種類型的散列。」我沒有看到這是可能的,因爲我指定了第三個參數。我的operator()過載看起來好嗎?試圖想想還有什麼可以的。編輯:沒關係,忘記在其他地方對不同的課程進行相同的修改。 – Stradigos